CS 595G: Hack Meetings
Shellphish
Me
This class
Requirements
SQL
username TEXT | lastname TEXT | password TEXT | id INTEGER |
paul | grosen | foo | 4 |
john | grosen | bar | 3 |
Table Creation
Inserting Rows
Selecting Rows
Interacting with an SQL engine (sqlite3)
The database object represents a connection to a database:
1 | db = sqlite3.connect(“sqlite3:////path/to/database.db”)
The “cursor” allows for manipulation of data:
2 | cursor = db.cursor()
The .execute method enables execution of queries:
3 | cursor.execute(“CREATE TABLE IF NOT EXISTS users (...)”)
If a statement is intended to make changes to the database, be sure to commit:
4 | db.commit()
Interacting with an SQL engine (sqlite3)
To get rows (e.g. via SELECT), also use .execute:
5 | cursor.execute(“SELECT * FROM users”)
Then grab the results using .fetchone or .fetchall:
6 | print cursor.fetchall()
The Row object, returned from a fetch, acts like a tuple and dictionary:
7 | print cursor.fetchone()[“id”]
Prepared statements
Sometimes, you might want to pass a value into a statement; for example, you might try:
8 | “SELECT * FROM users WHERE username=’%s’” % (creds[0])
Why should you NEVER, EVER do this?
Prepared statements
Sometimes, you might want to pass a value into a statement; for example, you might try:
8 | “SELECT * FROM users WHERE username=’%s’” % (creds[0])
Prepared statements
Instead, let the API pass the parameters to the engine for you:
8 | c.execute(“SELECT * FROM users WHERE username=’?’”, creds[0])
The 595G Server System
595G Servers
Please go add your handle and email to the sheet at
github.com/pcgrosen/595g-files/
This week