Using Python to read and write to Access

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

  1. import win32com.client

2. Establish a database connection

  1. conn = win32com.client.Dispatch(r"ADODB.Connection")
  2. DSN ='PROVIDER = Microsoft.Jet.OLEDB.4.0;DATA SOURCE = test.mdb'
  3. conn.Open(DSN)

3. Open a recordset

  1. rs = win32com.client.Dispatch(r'ADODB.Recordset')
  2. rs_name ='MEETING_PAPER_INFO'
  3. rs.Open('['+ rs_name +']', conn,1,3)

4. Operation on the record set

  1. rs.AddNew () #Add a new record
  2. 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

  1. #add _
  2. sql ="Insert Into [rs_name] (id, innerserial, mid) Values ('002133800088980002', 2, '21338')"#sql 语句
  3. conn.Execute ( sql ) #Execute sql statement _ _ _
  4. #delete _
  5. sql ="Delete * FROM "+ rs_name +" where innerserial = 2"
  6. conn.Execute(sql)
  7. #change _
  8. sql ="Update "+ rs_name +" Set mid = 2016 where innerserial = 3"
  9. conn.Execute(sql)

6. Traverse the record

  1. rs . MoveFirst () #The cursor moves to the first record
  2. count =0
  3. whileTrue:
  4.  if rs.EOF:
  5.  break
  6.  else:
  7.  for i in range(rs.Fields.Count):
  8.   #field name: field content
  9.   print(rs.Fields[i].Name, "", rs.Fields[i].Value)
  10.  count += 1
  11.  rs.MoveNext()

7、关闭数据库

  1. conn.close()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324915012&siteId=291194637