This document is high-level introduction to using pyodbc and does not cover all its details. pyodbc implements the Python Database API Specification v2.0, so you should read this specification for more information.
If you haven't installed pyodbc, download and install it.
First, you must import pyodbc. If you get errors here, make sure you have pyodbc installed.
import pyodbc
Next, create a connection by passing an ODBC connection string to the connect method. This step causes ODBC to load the database driver (the SQL Server driver in this example) and connect to the database.
cnxn = pyodbc.connect('DSN=northwind')
The ODBC connection string format is specified by ODBC in the SQLDriverConnect documentation. Unfortunately, this is for C programmers, but the comments section discussion of the connection string format is useful.
ODBC itself recognizes the following keywords in a connection string:
Each database driver may support additional keywords. For example, the SQL Server driver allows you to specify the machine SQL Server is running on using the SERVER keyword and the database to connect to using the DATABASE keyword. These two allow you to connect to the database without registering a DSN in the control panel. (The ODBC section of the SQL Native Client Using Connection String Keywords with SQL Native Client documentation may be useful when using SQL Server.)
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=user;PWD=password')
Next, we'll create a table and populate it with some example values. First, make a cursor and execute the necessary SQL. (The SQL may need to be modified for your database, particularly the type names like 'int'. I'm testing this using SQL Server.) Finally, commit the changes.
cursor = cnxn.cursor() cursor.execute("create table tmp(a int, b varchar(30))") cnxn.commit()
First, notice that the commit is applied to the connection, not the cursor. Changes from all cursors attached to the same connection will be commited. Also note that the commit is required. If you do not commit, the changes will be rolled back when the connection is closed.
Once you have a connection, obtain a cursor from it and execute a select statement via the
cursor's execute
method:
cursor = cnxn.cursor() cursor.execute('select a, b from tmp')