One plug, many sockets
You travel to another country. The wall sockets are different. You buy a travel adapter. Now your charger works.
Databases (organised stores of data) have the same problem. MySQL, Oracle and the others each work in a different way. You do not want to rewrite your program for each one.
So there are standard layers. Two common ones are JDBC and ODBC.
Key words
| Word | What it means |
|---|---|
| Database | An organised store of data that programs can search and change. |
| SQL | The language used to ask a database for data and to change it. |
| Query | A question or instruction written in SQL. |
| API | A set of ready-made tools one program offers to another. |
| JDBC | Java Database Connectivity. The standard way for Java programs to use a database. |
| ODBC | Open Database Connectivity. A standard way for programs in many languages to use a database. |
| Driver | A small piece of software that knows how to talk to one kind of database. |
| Driver manager | Software that picks the right driver for your connection. |
| Connection | An open link between your program and the database. |
| Statement | A part of your code that sends one query to the database. |
| Placeholder | A ? in a query that marks where a value goes. |
| Prepared statement | A statement with ? placeholders. The values are sent separately. It is safer and faster. |
| Result set | The rows the database sends back for a query. |
| Data source | A saved set of connection details with a name, used by ODBC. |
The cells students fill in are left blank in this preview.
The layers of JDBC
flowchart TD
app[Your Java program] --> api[JDBC core API: Connection, Statement, ResultSet]
api --> manager[Driver manager: finds the right driver]
manager --> d1[MySQL driver]
manager --> d2[Oracle driver]
d1 --> db1[(MySQL database)]
d2 --> db2[(Oracle database)]
Check: the layers
Have a go
Check: the layers
3 questionsJDBC in Java (read it)
import java.sql.*;
public class Shop {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://db:3306/shop";
try (Connection conn = DriverManager.getConnection(url, "student", "student")) {
String sql = "SELECT name, price FROM products WHERE price > ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setDouble(1, 10.0);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getDouble("price"));
}
}
}
}
}
}
Make a free account to save your work and track your progress.
The JDBC steps, line by line
| Step | JDBC | The same idea in Python |
|---|---|---|
| 1. Connect | DriverManager.getConnection(url, user, password) | sqlite3.connect(file) |
| 2. Prepare | conn.prepareStatement(sql) | the query with a ? placeholder |
| 3. Give the values | ps.setDouble(1, 10.0) | the tuple (10.0,) |
| 4. Run | ps.executeQuery() | conn.execute(query, values) |
| 5. Read the rows | while (rs.next()) ... | for row in result: ... |
| 6. Close | the try block closes everything | conn.close() |
The cells students fill in are left blank in this preview.
The same six steps in Python
import sqlite3
conn = sqlite3.connect(":memory:") # 1. connect
conn.execute("CREATE TABLE products (name TEXT, price REAL)")
conn.executemany("INSERT INTO products VALUES (?, ?)", [("Pen", 1.5), ("Bag", 24.0), ("Lamp", 12.0)])
query = "SELECT name, price FROM products WHERE price > ?" # 2. prepare
result = conn.execute(query, (10.0,)) # 3 and 4
for name, price in result: # 5. read the rows
print(name, price)
conn.close() # 6. close
Make a free account to save your work and track your progress.
The layers of ODBC
flowchart TD
app[Application: Excel, Python, C#...] --> manager[ODBC driver manager]
manager --> driver[ODBC driver for this database]
driver --> source[(Data source: server, database, user)]
manager -.->|reads the saved details| dsn[Data source name: ShopDSN]
ODBC from Python (read it)
# Needs the pyodbc package and an ODBC driver installed.
import pyodbc
import os
password = os.environ["DB_PASSWORD"] # the password comes from a setting, not from the code
conn = pyodbc.connect("DSN=ShopDSN;UID=student;PWD=" + password)
cursor = conn.cursor()
cursor.execute("SELECT name FROM products WHERE price > ?", 10.0)
for row in cursor.fetchall():
print(row.name)
conn.close()
Make a free account to save your work and track your progress.
JDBC and ODBC side by side
| JDBC | ODBC | |
|---|---|---|
| Used from | Java | Many languages: C, C#, Python, Excel |
| Layers | Your code, core API, driver manager, driver | Application, driver manager, driver, data source |
| Needs | A JDBC driver for your database | An ODBC driver and a data source on the computer |
| Connection details | A JDBC address, user and password | A data source name, or all the details written out |
| Safer queries | Prepared statements | Placeholders (?) |
The cells students fill in are left blank in this preview.
Match each part to its job
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Put the steps in order
Have a go
Put the steps in order
3 questionsWrite a small driver manager
A driver manager reads a connection string, finds the saved data source, and picks the right driver. Write a small one. A connection string looks like DSN=ShopDSN;UID=student;PWD=pw. Read the comments. Press Run Tests.
def parse_connection_string(text):
# Turn "DSN=ShopDSN;UID=student;PWD=pw" into {"DSN": "ShopDSN", "UID": "student", "PWD": "pw"}.
# Split on ";". Ignore empty parts. Split each part at the FIRST "=" only.
# Make every name upper case, so "dsn=x" gives the name "DSN".
return None
def find_source(sources, name):
# sources is a dictionary: data source name -> details.
# Give back the details for this name, or None if there is no such data source.
return None
def open_connection(sources, drivers, text):
# Work like a driver manager.
# 1. Read the connection string. 2. Find the data source named by DSN.
# 3. Find the driver: it is drivers[details["driver"]], a function.
# 4. Give back driver(details, user), where user is the UID (use "" if there is none).
# No such data source: give back "Data source not found".
# No such driver: give back "Driver not found".
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Choose a connection method
Choose the best way to connect in each case. Write the choice and one reason. 1. A Java app for a bank uses an Oracle database. 2. A manager wants live sales figures in a spreadsheet. 3. A small Python script reads a local file database. 4. A phone app needs data from a server owned by another company that gives you a web address and a key. Choose from JDBC, ODBC, a direct driver for the language, or a web API. Then write two sentences: why is a prepared statement better than joining the values into the query text yourself?
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go