1. Connect to the database
1) Connect directly to the database and create a cursor (the cursor)
cnxn = pyodbc.connect(‘DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass‘)cursor = cnxn.cursor()
2) Connect using DSN. The DSN connection usually does not require a password, or a PSW keyword is required.
cnxn = pyodbc.connect(‘DSN=test;PWD=password‘)cursor = cnxn.cursor()
There are more options for connection functions, and you can see more details in the PYODBC documentation for connect funtion and connectionstrings
2. Data query (SQL statement is select ... from). where
1) All SQL statements are run with the Cursor.execute function. If the statement returns a row, such as a row returned by a query statement, you can fetch the data through the FETCH function of the cursor, which has (fetchone,fetchall,fetchmany). If you return a blank line, the Fetchone function returns none, Fetchall and Fetchmany will return an empty column.
cursor.execute("select user_id, user_name from users")row = cursor.fetchone()if row: print row
2) Row This class, similar to a tuple, but they can also be accessed through the field name.
cursor.execute("select user_id, user_name from users")row = cursor.fetchone()print ‘name:‘, row[1] # access by column indexprint ‘name:‘, row.user_name # or access by name
3) If all the rows have been retrieved, then Fetchone will return none.
while 1: row = cursor.fetchone() if not row: break print ‘id:‘, row.user_id
4) When you use the Fetchall function, all remaining rows are returned, and if it is a blank row, an empty column is returned. (if there are many rows, doing so will consume a lot of memory.) Rows that are not read are compressed in the database engine and then sent in batches by the database server. Read only the rows you need at a time, which will greatly save memory space)
cursor.execute("select user_id, user_name from users")rows = cursor.fetchall()for row in rows: print row.user_id, row.user_name
5) If you are going to read all the data at once, then you can use the cursor itself.
cursor.execute("select user_id, user_name from users"):for row in cursor: print row.user_id, row.user_name
6) Since Cursor.execute returns a cursor, you can simplify the above statement to:
for row in cursor.execute("select user_id, user_name from users"): print row.user_id, row.user_name
7) There are many SQL statements that are not very convenient to write in a single line, so you can also use a three-quote string to write:
cursor.execute(""" select user_id, user_name from users where last_logon < ‘2001-01-01‘ and bill_overdue = ‘y‘ """)
3. Parameters
1) ODBC supports using a question mark as an argument in an SQL statement. You can add a value after the SQL statement to pass it to the question mark in the SQL statement.
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """, ‘2001-01-01‘, ‘y‘)
This is more secure than writing values directly into SQL statements, because each parameter is passed to the database separately. This is also more efficient if you run the same SQL statement with different parameters.
3) The Python DB API explicitly describes multiple parameters that can be passed using a sequence. PYODBC also supports:
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """, [‘2001-01-01‘, ‘y‘])
cursor.execute("select count(*) as user_count from users where age > ?", 21) row = cursor.fetchone() print ‘%d users‘ % row.user_count
4. Data insertion
1) data insertion, the Execute function that passes the SQL INSERT statement to the cursor, can accompany any required arguments.
cursor.execute("insert into products(id, name) values (‘pyodbc‘, ‘awesome library‘)")cnxn.commit()
cursor.execute("insert into products(id, name) values (?, ?)", ‘pyodbc‘, ‘awesome library‘)cnxn.commit()
Note Call the Cnxn.commit () function: You must call the Commit function, and no one will be invalidated for all operations on the database! When the connection is disconnected, all suspension modifications will be reset. This can easily lead to errors, so you must remember to call the Commit function.
5. Data modification and deletion
1) data modification and deletion is also the same as above, the SQL statement is passed to the Execute function. But we often want to know how many records are affected when the data is modified and deleted, and you can use the return value of Cursor.rowcount.
cursor.execute("delete from products where id <> ?", ‘pyodbc‘)print cursor.rowcount, ‘products deleted‘cnxn.commit()
2) Since the Execute function always returns the cursor, there are times when you can see a statement like this: (note rowcount on the last side)
deleted = cursor.execute("delete from products where id <> ‘pyodbc‘").rowcountcnxn.commit()
Also pay attention to calling the Cnxn.commit () function
6. Tips
1) Since the SQL statement using single quotes is valid, the double quotation marks are also valid:
deleted = cursor.execute("delete from products where id <> ‘pyodbc‘").rowcount
2) If you are using three quotes, you can also use this:
deleted = cursor.execute(""" delete from products where id <> ‘pyodbc‘ """).rowcount
3) Some databases (such as SQL Server) do not generate column names when counting, in which case you must use subscript when you want to access the data. Of course you can also use the "as" keyword to fetch a column name ("As Name-count" of the SQL statement below)
row = cursor.execute("select count(*) as user_count from users").fetchone()print ‘%s users‘ % row.user_count
4) If you just need a value, you can use the FETCH function in the same row to get all the data for the row and the first column.
count = cursor.execute("select count(*) from users").fetchone()[0]print ‘%s users‘ % count
If the column is empty, it will cause the statement to not run. The Fetchone () function returns none, and you will get an error: Nonetype does not support subscripts. If you have a default value, you can often use isnull, or merge nulls directly in the SQL database to override the default values.
maxid = cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]
In this example, if Max (ID) returns NULL,COALESCE (Max (ID), 0) will result in a query with a value of 0.
Pyodbc Simple to use