Download CS108 Lecture 19: The Python DBAPI

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
3/6/13
CS108 Lecture 19:
The Python DBAPI
Sqlite3 database
Running SQL and reading results in Python
Aaron Stevens
6 March 2013
Computer Science
What You’ll Learn Today
Computer Science
  Review: SQL
  Review: the Python tuple sequence.
  How does a custom application program connect
to a database?
  How to get user data into SQL queries?
  How does the application read the results of SQL
statements?
1
3/6/13
The Python tuple sequence
Computer Science
tuples are constructed by the comma
operator (not within square brackets), with or
without enclosing parentheses.
t = 4,5,6
print t
A single element tuple must have a trailing
comma, such as (d,).
The Python tuple sequence
Computer Science
tuples are very similar to lists, but they
are immutable: items in a tuple cannot be
changed.
tuple elements are accessed by index, or
by simultaneous assignment:
print t[0]
a,b,c = t # unpacking a tuple
2
3/6/13
The Python DB API
Computer Science
Python defines a standard API (objects and methods) for interaction with
databases.
  No standard implementation of this interface.
  3rd party developers write their own libraries which conforms to the standard.
We will be using 2 different DBMS in CS108:
  The SQLite3 DBMS comes standard with Python
  Free, nothing additional to install
  We ll move to the MySQL DBMS for web-application projects starting in 2
weeks
Creating a sqlite3
Connection
Computer Science
A Connection is an object that represents the
database connection.
  Import the sqlite3 module
  Use connection string to specify database file name.
  Call connect function to obtain a Connection.
3
3/6/13
Obtain a Cursor object
Computer Science
A Cursor object is an used to execute
transactions (via SQL) against the database.
  Create the Connection first…
  Ask the Connection object to give you a Cursor object:
Executing an SQL Statement
Computer Science
Use the Cursor object’s execute method to run
an SQL statement against the database.
Look at the results. What type are these?
4
3/6/13
Processing Query Results
Computer Science
After calling the cursor.execute() method, we can process/interpret
the results.
SELECT queries:
results will be zero or more rows of data returned from the database
INSERT, UPDATE, and DELETE queries:
the result will be the number of rows
(zero or more) affected by the change.
Processing Query Results
Computer Science
SELECT queries:
results will be zero or more rows of data returned from the
database
The method cursor.fetchall() returns a
tuple of rows (each row is a tuple of fields).
data = cursor.fetchall()
We can then process this tuple in the normal
fashion using a for loop.
5
3/6/13
Processing Query Results
Computer Science
A complete example, processing all rows returned
from a SELECT query:
Processing Query Results
Computer Science
INSERT, UPDATE, and DELETE queries:
the result will be the number of rows
(zero or more) affected by the change.
The attribute cursor.rowcount is an
integer, the number of rows affected.
6
3/6/13
How to Commit the Changes?
Computer Science
For INSERT, UPDATE, and DELETE queries, you need to
execute the method: conn.commit()
on the Connection object to commit your changes.
It might be a good idea to only commit if the row
count is reasonable (e.g. 1, not 2728).
Parameterized SQL
Computer Science
Most likely, SQL queries in an application will be
dependent on some data input by the user.
Don t do this:
This kind of statement is vulnerable to SQL injection
– a major security risk.
7
3/6/13
SQL Injection
Computer Science
SQL injection is a technique that exploits the syntax of SQL
to chain extra statements to an SQL query.
Suppose user inputs:
BUD ;DROP TABLE stocks AND t = t
The resulting SQL becomes:
SELECT * from stocks
WHERE symbol= BUD ;DROP TABLE stocks AND
t = t
Don t think the hackers haven t tried this!
Parameterized SQL
Computer Science
Instead, do this:
and put the input parameter into a tuple:
8
3/6/13
Parameterized SQL
Computer Science
Also, use parameterized SQL for INSERT statements.
  (assume variables symbol, name, price, earnings, yield
have received user input):
sql = INSERT INTO stocks VALUES (?,?,?,?,?)
parameters = (symbol,name,price,earnings,yield)
cursor.execute(sql, parameters)
SQL Injection
Computer Science
9
3/6/13
SQL Injection
Computer Science
Source: www.xkcd.com
What You Learned Today
Computer Science
  tuple
  DBAPI
  Connection object
  Cursor object
  SQL injection!
10
3/6/13
Announcements and To Do
Computer Science
  Readings:
  SQL Tutorial (Monday) http://www.firstsql.com/tutor.htm
  Python DBAPI and sqlite3 (today)
http://docs.python.org/library/sqlite3.html
Using sqliteClient Program
Computer Science
You may use the sqliteClient.py program to
experiment with SQL statements:
http://cs-webapps.bu.edu/cs108/util/sqliteClient.py
  Check your SQL statements against this client to rule out
SQL syntax errors.
  Then implement the SQL with parameterized data in your
client program.
11