In the process of learning Python , we will encounter the problem of reading and writing Access . At this time, we can use the COM component access function of the win32.client module to operate Access files through ADODB .
1. Import the module
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 recordset
rs = win32com . client . Dispatch ( r 'ADODB.Recordset' )
rs_name = 'MEETING_PAPER_INFO'
rs . Open ( '[' + rs_name + ']' , conn , 1 , 3 )
4. Operation on the record set
rs.AddNew () #Add a new record
rs . Fields . Item ( 0 ). Value = "data" #The first record of the new record is "data"
rs.Update ( ) #Update _ _
5. Use SQL statements to add, delete, and modify data
#add _
sql = "Insert Into [rs_name] (id, innerserial, mid) Values ('002133800088980002', 2, '21338')" #sql 语句
conn.Execute ( sql ) #Execute sql statement _ _ _
#delete _
sql = "Delete * FROM " + rs_name + " where innerserial = 2"
conn . Execute ( sql )
#change _
sql = "Update " + rs_name + " Set mid = 2016 where innerserial = 3"
conn . Execute ( sql )
6. Traverse the record
rs . MoveFirst () #The cursor moves to the first record
count = 0
while True :
if rs . EOF :
break
else :
for i in range ( rs . Fields . Count ):
#field name: field content
print(rs.Fields[i].Name, " : ", rs.Fields[i].Value)
count += 1
rs.MoveNext()
7 、关闭数据库