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
2. Establish a database connection
1 2 3 | conn = win32com.client.Dispatch(r "ADODB.Connection" )
DSN = 'PROVIDER = Microsoft.Jet.OLEDB.4.0;DATA
SOURCE = test.mdb'conn.Open(DSN)
|
Copy after login
3. Open a record set
1 2 3 | rs = win32com.client.Dispatch(r 'ADODB.Recordset' )
rs_name = 'MEETING_PAPER_INFO' rs.Open( '[' +
rs_name + ']' , conn, 1, 3)
|
Copy after login
4. Operate the record set
1 2 3 | rs.AddNew() #添加一条新记录
rs.Fields.Item(0).Value = "data" #新记录的第一个字段设为
"data" rs.Update() #更新
|
Copy after login
5. Use SQL statements to add, delete, and modify data
1 2 3 4 5 6 7 8 9 | # 增
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)
|
Copy after login
6. Traverse records
1 2 3 4 5 6 7 8 9 10 11 | 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()
|
Copy after login
7. Close the database
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!