Read Access Databases with Python

zhaozj2021-02-16  89

There are many ways to program database programming with Python language, seeing the article with WiFH_178 with Python to implement database programming. This article will use ADO (ActiveX Data Object) to read Access Database (MDB) files!

First in the IDE (this is pythonwin), reference Microsoft ActiveX Data Objects Library, click Tools ------> Com makepy utility

Figure:

SELECT LIBRARY

To select Microsoft ActiveX Data Objects Library, you can generate a .py file by makepy.

We can create a new Python script file, code

Import win32com.client conn = win32com.client.dispatch ('adoDb.connection') DSN = 'provider = microsoft.jet.oledb.4.0; data source = c: /db.mdb;' conn.open (dsn) = win32com.client.Dispatch ( 'ADODB.Recordset') rs_name = 'co' rs.Open ( '1', conn, 1,3) # 1 and a 3 are constants representative of adOpenKeyset and adLockOptimistadLockOptimisticflds = {} rs.MoveFirst () Count = 0WHILE NOT RS.EOF: for x in Range (rs.fields.count): flds [x] = rs.fields.Item (x) .value print "------------- ------------ "Print" |% s |% s |% s |% s | "% (FLDS [0], FLDS [1], FLDS [2], FLDS [3] ) Count = count 1 rs.movenext () Print "Record Count:% D"% (count,) # conn.close ()

Import the Win32com.Client module using the import statement so that we use ADO

After the above settings, you can directly connect the database.

Define a dictionary (Dictionary), which is one of Python's built-in data type, which defines a one-on-one relationship between keywords and values. This is like the associated array in Perl, the Map in Java, or the scripting.dictionary object in VBSCIPT. Here, an empty dictionary is used to store the value of the field in the database.

Traverse the entire data set, print data information

Print "|% s |% s |% s |% s |"% (FLDS [0], FLDS [1], FLDS [2], FLDS [3]) is formatted and printed. Python supports the formatting of the value to the string, like the Sprintf function in the C language. The most basic usage is to simply insert a value in the% s placeholder.

Save, run

The result is:

转载请注明原文地址:https://www.9cbs.com/read-12204.html

New Post(0)