< Back to Start

How to access two databases with one method?

welw's blog

welw✉️ 20260913

I was in a situation where it was necessary to access two or more databases to obtain data. The two databases contain essentialy similar data. A client used one database schema but would like to migrate to another, more modern. So I need two completely different SQL queries to access these machines. For first database I would need to pick data using simple SELECT * FROM query, for the other one, I would need to go through lots of joins.

How does one solve it?

By Object Oriented Programming of course!

I created two classes: DatabaseService1 and DatabaseService2. Each of the classes have publicly available GetData. Now I can create an interface IDatabaseService, so each class implements my method, so database access should be unified, and I don’t need to think about these pesky joins any more.

Now I was asked: does a piece of data exist in any of the tables?

This is where I got lazy. I decided to create yet another instance of the same interface and use both database interfaces as arguments to constructor.

Was it wise? I don’t know. Was it fast? Yep.