What is the Python equivalent to DatabaseMetaData
-
1There isn't an exact equivalent. What information are you trying to pull and what type of database is it? – Jason Coon May 18 '09 at 17:16
-
I need to be able to get tables, columns (size, scale, type, name), foreign keys, primary keys from Oracle and also MySQL. – Joshua May 19 '09 at 14:48
2 Answers
This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help.
The ANSI SQL-92 and SQL-99 Standard requires the INFORMATION_SCHEMA schema, which stores information regarding the tables in a catalog.
The metadata you seek can be retrieved with a query on views in that schema.
for example:
select column_name, is_nullable, data_type, character_maximum_length as maxlen
from information_schema.columns
where table_name = 'Products'
Not all databases implement that part of the standard. Oracle, for example, does not.
Fortunately, there are also database-specific tables that store that kind of info.
While Microsoft SQL Server supports the Information_Schema thing, there are also SQL Server-specific tables that give more metadata information. These are [CatalogName].dbo.sysobjects
and [CatalogName].dbo.sysolumns
. Similar queries on these tables will give you the metadata you seek. Example:
select * from [CatalogName].dbo.syscolumns
where id =
(Select id from [CatalogName].dbo.sysobjects where name = 'Products')
In Oracle, the ALL_TAB_COLUMNS table can give you the information:
select column_name, data_type, data_length, data_precision, data_scale
from ALL_TAB_COLUMNS
where table_name = 'EMP';
Whether you query the standard views or the db-specific views, you don't need ODBC to do these queries - you can use whatever db connection you have available for operational data, subject to security approvals of course.

- 189,189
- 101
- 473
- 713
-
Oracle of course does not seem to have this... It appears I will need to go the ODBC route to get a standard set of functionality between dbs. – Joshua May 18 '09 at 20:46
-
Hmm, that's a surprise! With Oracle, there is an alternative data table you can query. I'll update the answer to indicate that. – Cheeso May 18 '09 at 22:20
If your willing to use ODBC for data access then you could use pyodbc, http://code.google.com/p/pyodbc/wiki/Features. Pyodbc allows you to call functions like SQLTables, which is equivalent to the JDBC getTables function. The JDBC and ODBC functions to get to metadata are extremely similar.

- 2,094
- 12
- 14