In the process of learning Python, we encounter access read and write problems, we can take advantage of the Win32.client module COM component Access function, through the ADODB operation Access files.
1. Import Module
Import Win32com.client
2. Establish database connection
conn = Win32com.client.Dispatch (r "ADODB. Connection ") DSN = ' PROVIDER = microsoft.jet.oledb.4.0;data SOURCE = Test.mdb ' Conn. Open (DSN)
3. Open a record set
rs = Win32com.client.Dispatch (R ' ADODB. Recordset ') rs_name = ' Meeting_paper_info ' Rs. Open (' [' + Rs_name + '] ', conn, 1, 3)
4. Operation on recordset
Rs. AddNew () #添加一条新记录rs. Fields.item (0). Value = "Data" #新记录的第一个字段设为 "Data" Rs. Update () #更新
5, using SQL statements to increase, delete, change data
# Add sql = "Insert into [rs_name] (ID, innerserial, mid) Values (' 002133800088980002 ', 2, ' 21338 ')" #sql语句conn. Execute (SQL) #执行sql语句 # Delete sql = "Delete * from" + Rs_name + "where innerserial = 2" conn. Execute (SQL) # changed to sql = "Update" + Rs_name + "Set mid =" where innerserial = 3 "conn. Execute (SQL)
6. Traverse Record
Rs. MoveFirst () #光标移到首条记录count = 0while True: if Rs. EOF: break else: for I in range (Rs. Fields.Count): #字段名: Field contents Print (Rs. Fields[i]. Name, ":", Rs. Fields[i]. Value) count + = 1 rs. MoveNext ()
7. Close the database
Conn.close ()