This example analyzes the basic steps of Python operations Access database. Share to everyone for your reference, specific as follows:
The advent of the Python programming language brings great benefits to developers. We can use such a powerful object-oriented open source language to easily achieve a number of specific functional requirements. such as Python operations Access database functionality implementation, and so on. Before Python operates an Access database, you should first install the Python and Python for Windows extensions.
Step 1, establish the database connection
Import win32com.client
conn = Win32com.client.Dispatch (R ' ADODB. Connection ')
DSN = ' Provider=Microsoft.Jet.OLEDB.4.0;Data source=c:/mydb.mdb; '
Conn. Open (DSN)
Step 2, open a recordset
rs = Win32com.client.Dispatch (R ' ADODB. Recordset ')
rs_name = ' myrecordset ' #表名
Rs. Open (' [' + Rs_name + '] ', conn, 1, 3)
Step 3, Operations on recordsets
Rs. AddNew ()
Rs. Fields.item (1). Value = ' data '
Rs. Update ()
Step 4, insert or update data with SQL
conn = Win32com.client.Dispatch (R ' ADODB. Connection ')
DSN = ' Provider=Microsoft.Jet.OLEDB.4.0;Data source=c:/mydb.mdb; '
sql_statement = "Insert into [table_name] ([field_1],
[field_2]) VALUES (' data1 ', ' data2 ')"
Conn. Open (DSN)
Conn. Execute (sql_statement)
Conn. Close ()
Step 5, traverse the record
Rs. MoveFirst ()
count = 0 while
1:
if Rs. EOF:
break
else:
countcount = count + 1
Rs. MoveNext ()
Note: If a record is empty, moving the pointer to the first record will result in an error because the RecordCount is not valid at this time. The workaround is to set the CursorLocation to 3 before opening a recordset, and then open the Recordset, at which point the RecordCount will be valid. For example:
Rs. CursorLocation = 3 # don ' t use parenthesis here
Rs. Open (' Select * FROM [table_name] ', conn) # was sure Conn is open
Rs. RecordCount # no parenthesis here either
More information about Python-related content can be viewed in this site: "The python common Database operation tips Summary", "Python+mysql Database Program Design Primer", "python Picture Operation skills Summary", "Python data structure and Algorithms tutorial", " Python socket Programming Tips, Summary of Python function usage tips, python string manipulation tips, Python introductory and Advanced classic tutorials, and Python file and directory how-to tips
I hope this article will help you with Python programming.