Use Python to read and write Access and pythonaccess to read and write

Source: Internet
Author: User

Use Python to read and write Access and pythonaccess to read and write

When learning Python, we will encounter Access read/write problems. In this case, 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. operations 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 ('000000', 2, '000000')" # SQL statement conn. execute (SQL) # Execute SQL statement # Delete SQL = "Delete * FROM" + rs_name + "where innerserial = 2" conn. execute (SQL) # modify SQL = "Update" + rs_name + "Set mid = 2016 where innerserial = 3" conn. execute (SQL)

6. Traverse records

Rs. moveFirst () # move the cursor 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. Shut down the database

conn.close()

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.