Opening a database from code
After this: Connect to a database file, send SQL, read the rows back, and run the program twice.
On this page · 5 sections · 3 checks
In the earlier tutorials of this learning path you typed SQL into a box on the page and read the answer in a table. A real app does not have you typing SQL. A program sends the SQL, reads the answer, and shows it to the user. How does a Python or Java program do that?
A program that talks to a database
The idea has three parts. The program opens a line to the database, sends it SQL as text, and reads the rows that come back. The open line is called a .
SQLite keeps a whole database in one file. In this tutorial the file is called marks.db, and it sits in the same folder as the program. Python has SQLite built in: the module sqlite3 comes with Python, and import sqlite3 is all a program needs.Java talks to every database through one standard set of classes called JDBC, in the package java.sql. Each database also needs a driver: a library that knows how to talk to that one database. For SQLite it is sqlite-jdbc, which you download and put on the class path.
Here is the first program, step by step:
- Open a connection to
marks.db. If the file does not exist, SQLite creates it, empty. - Send
CREATE TABLE IF NOT EXISTS students …. The wordsIF NOT EXISTSmean: make the table only if it is not there yet. - Send two INSERTs, one for Ana and one for Ben. The database gives them the ids 1 and 2.
- Save the changes. In Python this is the line
conn.commit(). Java saves each change the moment it runs, so the Java program has no such line. - Send a SELECT and go through the rows it returns, one row per turn of the loop, printing each.
- Close the connection.
- Run the programRun it and step through. The first lines send SQL and change nothing in the Variables panel: the work happens inside the database. Then watch the loop: each turn fills two boxes from one row of the answer, and the next line prints them.
import sqlite3
conn = sqlite3.connect("marks.db")conn.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")conn.execute("INSERT INTO students (name) VALUES ('Ana')")conn.execute("INSERT INTO students (name) VALUES ('Ben')")conn.commit()for student_id, name in conn.execute("SELECT id, name FROM students ORDER BY id"): print(student_id, name)conn.close()run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The loop line does two jobs at once. for student_id, name in conn.execute(…) sends the SELECT and then hands over one row per turn, split into the two boxes.executeQuery sends the SELECT and gives back a ResultSet. Each rs.next() moves to the next row and says whether there was one; rs.getInt("id") and rs.getString("name") read its columns by name. The program prints 1 Ana and 2 Ben.
Python and Java do not run on this page in this tutorial. The browser's Python here has no sqlite3, and Java does not run in the browser at all. Step through the traces, and run the programs on your computer to see them for real. The SQL itself does run here, in the block below: it is the same SQL the program sends, on a fresh database.
Saving: commit
Sending an INSERT is not the same as keeping it. Since the tutorial on changing data, you know that a transaction groups changes so that they all happen or none do. When a program changes data, a transaction is open until the program says what to do with it.
To is to make the changes permanent. Python's sqlite3 starts a transaction by itself before an INSERT, UPDATE or DELETE, and keeps it open until you call conn.commit(). If the program closes the connection without it, the changes are thrown away.JDBC starts every connection in autocommit mode: each statement is its own transaction and is committed the moment it runs. Lesson 3 turns this off when two changes must happen together.
Running it twice
The rows are in marks.db, a file on the disk. When the program ends, its variables are gone, but the file stays. Run the program a second time and it opens the same file, where Ana and Ben are already waiting. It adds them again, with the next free ids, and the SELECT reads all four rows:
1 Ana2 Ben3 Ana4 BenThat is the point of a database: the data outlives the program. It is also a bug in this little program, which adds the same two people every time it runs. Lesson 4 comes back to it.
Check yourself
The program runs in a folder with no file called marks.db. What does the line conn = sqlite3.connect("marks.db")Connection conn = DriverManager.getConnection("jdbc:sqlite:marks.db"); do?
The program above ran once and printed 1 Ana and 2 Ben. You run it again, in the same folder. What does the second run print?
import sqlite3
conn = sqlite3.connect("marks.db")conn.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")conn.execute("INSERT INTO students (name) VALUES ('Ana')")conn.execute("INSERT INTO students (name) VALUES ('Ben')")conn.commit()for student_id, name in conn.execute("SELECT id, name FROM students ORDER BY id"): print(student_id, name)conn.close()import java.sql.*;
public class Main { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite:marks.db"); Statement st = conn.createStatement(); st.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); st.execute("INSERT INTO students (name) VALUES ('Ana')"); st.execute("INSERT INTO students (name) VALUES ('Ben')"); // No commit line: JDBC saves each change the moment it runs. ResultSet rs = st.executeQuery("SELECT id, name FROM students ORDER BY id"); while (rs.next()) { int studentId = rs.getInt("id"); String name = rs.getString("name"); System.out.println(studentId + " " + name); } conn.close(); }}The program has ended. Where are the rows for Ana and Ben now?
Honesty notes
- Open a connection to a SQLite file from Python (sqlite3.connect) or Java (DriverManager.getConnection with a jdbc:sqlite: address and the sqlite-jdbc driver).
- Send SQL through the connection and go through the rows of a SELECT one at a time.
- Commit to make changes permanent: Python's sqlite3 waits for commit(), while JDBC commits each statement at once unless autocommit is turned off.
- Say why the rows are still there on the next run: they live in the database file, not in the program's variables.