I am using pyodbc to connect to various odbc compliant databases.
Suppose a MySql database has name, age, nationality in it. Now my requirement is that i have to produce a dictionary containing the records in it as for example:
{'Name' : 'a', 'Age' : '20'}
if the query specified in the execute() method of pyodbc object.
What i did to get the colums headers i.e “Name”, “Age” is that i created a new table out of the select query and then used
select column_name from information_schema.columns where table_name=xxx
to get the column headers. I dont know if the queries ‘create table‘, ‘drop table‘ and ‘select column name ….’ command are all same for the odbc compliant databases. I checked for PostgreSql and MySql, the work fine, but if they are different, then i need to change my implementation and will be like:
if mysql:
execute(this)
if posegresql:
execute(this)
if ibmdb2:
execute(this)
if the queries i mentioned above are same for all databases, then there is no problem, but if they are different, what can be the easy and efficient solution?
There is many problems in one question.
At first there is DB-API which standardize some things and one of them is
descriptionof columns you got withSELECT. You should not useinformation_schemafor such things. What will you show if you use columns from other tables, or just showCOUNT(*)? This is how to usedescriptionto obtain column names (tried withpyodbcand Northwind MS Access database):As for SQL then no, every database has its own dialect. Some of it is common, but there are many differences. For example datetime strings can be quite different.
Of course you can use database via DAL: https://en.wikipedia.org/wiki/Database_abstraction_layer , but I used only DAL from web2py. I think use of such existing DAL would be simplest think if you want to build something bigger and database independent. ODBC and similar standards like JDBC are only way to connect to database, do some queries or execute other statements, check metadata (column names etc), but they do not hide SQL dialect differences.