This article analyzes the basic steps of Python operating Access database. Share to everyone for your reference, as follows:
The advent of the Python programming language brings great benefits to developers. We can make use of such a powerful object-oriented open-source language to easily implement many specific functional requirements. For example, Python operation Access database function implementation and so on. Before Python operates an Access database, you should first install Python and Python for Windows extensions.
Step 1, establish the database connection
Import Win32com.clientconn = 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, record set operations
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 = 0while 1:if Rs. EOF:breakelse:countcount = Count + 1rs. MoveNext ()
Note: If a record is empty, moving the pointer to the first record will result in an error because RecordCount is not valid at this time. The workaround is to set CursorLocation to 3 before opening a recordset and then open the Recordset, at which point RecordCount will be valid. For example:
Rs. CursorLocation = 3 # don ' t use parenthesis herers. Open (' Select * FROM [table_name] ', conn) # are sure Conn is Openrs. RecordCount # no parenthesis here either