Basic steps for Python Operations Access database analysis

Source: Internet
Author: User
Tags dsn
This article analyzes the basic steps of Python operating Access database. Share to everyone for your reference, as follows:

The advent of the Python programming language brings great benefits to developers. We can make use of such a powerful object-oriented open-source language to easily implement many specific functional requirements. For example, Python operation Access database function implementation and so on. Before Python operates an Access database, you should first install Python and Python for Windows extensions.

Step 1, establish the database connection

Import Win32com.clientconn = Win32com.client.Dispatch (R ' ADODB. Connection ') DSN = ' Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/mydb.mdb; ' Conn. Open (DSN)

Step 2, open a recordset

rs = Win32com.client.Dispatch (R ' ADODB. Recordset ') rs_name = ' Myrecordset ' #表名rs. Open (' [' + Rs_name + '] ', conn, 1, 3)

Step 3, record set operations

Rs. AddNew () Rs. Fields.item (1). Value = ' data ' Rs. Update ()

Step 4, insert or update data with SQL

conn = Win32com.client.Dispatch (R ' ADODB. Connection ') DSN = ' Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/mydb.mdb; ' sql_statement = "Insert into [table_name] ([field_1],[field_2]) VALUES (' data1 ', ' data2 ')" Conn. Open (DSN) Conn. Execute (sql_statement) Conn. Close ()

Step 5, traverse the record

Rs. MoveFirst () Count = 0while 1:if Rs. EOF:breakelse:countcount = Count + 1rs. MoveNext ()

Note: If a record is empty, moving the pointer to the first record will result in an error because RecordCount is not valid at this time. The workaround is to set CursorLocation to 3 before opening a recordset and then open the Recordset, at which point RecordCount will be valid. For example:

Rs. CursorLocation = 3 # don ' t use parenthesis herers. Open (' Select * FROM [table_name] ', conn) # are sure Conn is Openrs. RecordCount # no parenthesis here either


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.