Detailed explanation of Access read and write operations using Python

高洛峰
Release: 2017-03-31 10:06:51
Original
4295 people have browsed it

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
Copy after login

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)
Copy after login

3. Open a record set

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

rs.AddNew()  #添加一条新记录
rs.Fields.Item(0).Value = "data"  #新记录的第一个字段设为
"data"rs.Update()  #更新
Copy after login

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)
Copy after login

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()
Copy after login

7. Close the database

conn.close()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!