In the process of learningPython, we will encounter Access reading and writing problems. At this time, we can use the COM component access function of the win32.client module to operate Access files through ADODB.
1. Import module
import win32com.client
2. Establish a 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. Operate the record set
rs.AddNew() #添加一条新记录 rs.Fields.Item(0).Value = "data" #新记录的第一个字段设为 "data"rs.Update() #更新
5. Use SQL statements to add, delete, and modify data
# 增 sql = "Insert Into [rs_name] (id, innerserial, mid) Values ('002133800088980002', 2, '21338')" #sql语句 conn.Execute(sql) #执行sql语句 # 删 sql = "Delete * FROM " + rs_name + " where innerserial = 2" conn.Execute(sql) # 改 sql = "Update " + rs_name + " Set mid = 2016 where innerserial = 3" conn.Execute(sql)
6. Traverse records
rs.MoveFirst() #光标移到首条记录 count = 0 while True: if rs.EOF: break else: for i in range(rs.Fields.Count): #字段名:字段内容 print(rs.Fields[i].Name, ":", rs.Fields[i].Value) count += 1 rs.MoveNext()
7. Close the database
conn.close()
The above is the detailed content of Detailed explanation of Access read and write operations using Python. For more information, please follow other related articles on the PHP Chinese website!