SQLite Guide @ Coding:
Wanting to get your hands dirty with databases? Well starting out with SQLite is a good idea.
Note
The way we are teach SQLite is different. This is because we want you to avoid fearing about SQL Injection(s). We do belive that teaching this method saves new coders time.
1. Create a DB file.
- Create a
database.dbfile.
2. Connecting:
To get started you must connect to your database and setup a "cursor".
- In your Python file import the sqlite module. (a built-in module after Python
2.5and is actually calledsqlite3) - Using the the sqlite module do:
database = sqlite3.connect("database.db") - The add on another line:
curosr = database.cursor()
Code Example:
3. Creating a Table:
Now that you have a cursor, you are able to execute SQL Commands. The first instruction should be to create a table if there is no tables.
- Boolean is either
TrueorFalse
4. Modifying, Adding and Removing:
Adding:
- To add a row of data to a database add
INSERT INTOthen the table name then in brackets the value names(name, attendance)then addVALUES (?, ?)in the speech marks. - Then add a comma and add in brackets the data you want to add in the correct order
name = "John"
attendance = False
cursor.execute("INSERT INTO register (name, attendance) VALUES (?, ?)", (name, attendance))
Deleting:
- To delete data from the table do
DELETE FROMthen the database name. But just doing this will delete all the rows of data. To stop this we need to add aWHEREstatement.
Warning
If "Laura" was added in all lower cases then the database would not delete that row. It is case senstive. We reccomend you make all string variable lower case. Simply add:
Modifying
- To modify a the table do:
UPDATE register SET attendance = ? WHERE name = ?.- The
WHEREstatement prevents every single row of data being updated.
- The