Python Forum

Full Version: Comparing the count of rows from the tables that are present in two different databas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Say for example I have a database named A and B with same table name and with different set of records. I want to compare the count of the table 1 that is present in Database A and B.

Database A has 190 tables and Database B has 190 tables with same table names. But table 1 has 40 records in Database A and table 1 in Database 2 has 30 records.

As of now I am able to do that in SQL server with this query. select (select count() from A.table1) as Count1, (select count() from B.table1) as Count2

But I am trying to do the same in Python. How can I connect to the two databases with the same conn object and use it to count the table records in different databases. I would also thankful if someone can help me to automate these for all the tables in both the databases.Thank you.
show what you've tried (as code)
import pyodbc
conn1=pyodbc.connect('Driver={SQL Server};'
                   'Server=[server name];'
                   'Database=A;'
                   'Trusted_Connection=yes;')
conn2=pyodbc.connect('Driver={SQL Server};'
                   'Server=[server name];'
                   'Database=B;'
                   'Trusted_Connection=yes;')
cursor=conn1.cursor()
cursor.execute('select count(*) from A.table1')
for row in cursor:
    print(row)
what errors (or results) --- please use BBcode tags
Hey Larz,

If you have gone through my code, the code is connecting to two tables in different databases using two con objects. There would be no error. But I cannot achieve the functionality I am looking for that is I cannot query from two tables using two different connection objects. So I want some help in getting a single con object where it can connect to the two different databases.

Thank you
which database are you using?
is there a reason why you are using ODBC?
I am trying to connect to sql server...