How to get datatypes of specific fields of an Access database using pyodbc?

不想你离开。 提交于 2019-11-29 17:32:33
Conrad Frix

The reason why those articles aren't helping you is because they are for SQL Server. SQL Server has system tables that you can query to get the column data, MS Access doesn't. MS Access only lets you query the object names.

However ODBC does support getting the schema through its connection via the ODBC.SQLColumns functions.

According to this answer PyODBC exposes this via a cursor method

# columns in table x
for row in cursor.columns(table='x'):
    print row.column_name 

As Mark noted in the comments you probably also want the row.data_type. The link he provided includes all the columns it provides

  1. table_cat
  2. table_schem
  3. table_name
  4. column_name
  5. data_type
  6. type_name
  7. column_size
  8. buffer_length
  9. decimal_digits
  10. num_prec_radix
  11. nullable
  12. remarks
  13. column_def
  14. sql_data_type
  15. sql_datetime_sub
  16. char_octet_length
  17. ordinal_position
  18. is_nullable: One of SQL_NULLABLE, SQL_NO_NULLS, SQL_NULLS_UNKNOWN.

I am not familiar with pyodbc, but I have done this in VBA in the past.

The 2 links you mentionned are for SQL Server, not for Access. To find out the data type of each field in an Access table, you can use DAO or ADOX.

Here is an example I did, in VBA with Excel 2010, where I connect to the Access database (2000 mdb format) and list the tables, fields and their datatypes (as an enum, for example '4' means dbLong). You can see in the output the system tables and, at the bottom, tables created by the user. You can easily find examples on internet for how to do something similar with ADOX. I Hope this helps.

Private Sub TableDefDao()
    Dim db As DAO.Database
    Set db = DAO.OpenDatabase("C:\Database.mdb")

    Dim t As DAO.TableDef
    Dim f As DAO.Field
    For Each t In db.TableDefs
        Debug.Print t.Name
        For Each f In t.Fields
            Debug.Print vbTab & f.Name & vbTab & f.Type
        Next
    Next
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!