fig: DB data-type arguments
import sqlite3
# Fetch some student records from the database.
db = sqlite3.connect("students")
c = db.cursor()
query = "select name, id from students order by name;"
c.execute(query)
rows = c.fetchall()
# First, what data structure did we get?
print "Row data:"
print rows
# And let's loop over it too:
print
print "Student names:"
for row in rows:
print " ", row[0]
db.close()
import sqlite3
db = sqlite3.connect("testdb")
c = db.cursor()
c.execute("insert into balloons values ('blue', 'water') ")
db.commit()
db.close()
send query to DB
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("select content, time from posts order by time desc")
posts = c.fetchall()
db.close()
insert to DB
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("insert into posts values (%s)", (content,))
db.commit()
db.close
'); delete from posts; --
can be submitted to forms, which erase entire DBs if the form input is not sanitizedpython
string concatenation (+)
or string parameters interpolation (%)
to pass variables to a SQL queryexecute()
method to pass a tupledelete from DB
UPDATE table-name SET column-name = 'benign-value' WHERE column-name LIKE '%spam%';
DELETE FROM table-name WHERE column-name = 'benign-value';
<script>
setTimeout(function() {
var tt = document.getElementById('content');
tt.value = "<h2 style='color: #FF6699; font-family: Comic Sans MS'>Spam, spam, spam, spam,<br>Wonderful spam, glorious spam!</h2>";
tt.form.submit();
}, 2500);
</script>
creating empty tables:
CREATE TABLE table-name (
id serial primary key,
col1-name *type* ,
col2-name *type* , ...);
CREATE TABLE table-name (
col1-name *type* ,
col2-name *type* ,
col3-name *type* , ...
primary key (col1-name, col2-name)
);
primary key in SQL is used as a unique row identifier
CREATE TABLE table-name (
col1-name *type* \[constraints\],
col2-name *type* \[constraints\],...,
\[row constraints\]);
timestamptz
(postgreSQL only) == timestamp with time zone
(SQL standard type name) CREATE TABLE sales (
sku text REFERENCES products,
sale_date data,
count integer
);
sku text REFERENCES products(sku)
these are referred to as foreign keys
REFERENCES
key to relate columns -- table 1
CREATE TABLE students(
id SERIAL PRIMARY KEY,
name TEXT
);
-- table 2
CREATE TABLE courses(
id TEXT PRIMARY KEY,
name TEXT
);
-- table 3
CREATE TABLE grades(
student INTEGER REFERENCES students(id);
course TEXT REFERENCES courses(id);
grade TEXT
);
/*
the REFERENCES key here relate
- student of grades : id of students
- course of grades : id of courses
these are the foreign keys
*/
deleting tables:
DROP TABLE name[options];
creating and dropping DBs:
CREATE DATABASE name[options];
DROP DATABASE name[options];