Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 6.3 (3 of 3): JDBC and ODBC

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it means
DatabaseAn organised store of data that programs can search and change.
SQLThe language used to ask a database for data and to change it.
QueryA question or instruction written in SQL.
APIA set of ready-made tools one program offers to another.
JDBCJava Database Connectivity. The standard way for Java programs to use a database.
ODBCOpen Database Connectivity. A standard way for programs in many languages to use a database.
DriverA small piece of software that knows how to talk to one kind of database.
Driver managerSoftware that picks the right driver for your connection.
ConnectionAn open link between your program and the database.
StatementA part of your code that sends one query to the database.
PlaceholderA ? in a query that marks where a value goes.
Prepared statementA statement with ? placeholders. The values are sent separately. It is safer and faster.
Result setThe rows the database sends back for a query.
Data sourceA 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

JDBC in Java (read it)

Code: java
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

StepJDBCThe same idea in Python
1. ConnectDriverManager.getConnection(url, user, password)sqlite3.connect(file)
2. Prepareconn.prepareStatement(sql)the query with a ? placeholder
3. Give the valuesps.setDouble(1, 10.0)the tuple (10.0,)
4. Runps.executeQuery()conn.execute(query, values)
5. Read the rowswhile (rs.next()) ...for row in result: ...
6. Closethe try block closes everythingconn.close()

The cells students fill in are left blank in this preview.

The same six steps in Python

Code: 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)

Code: python
# 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

JDBCODBC
Used fromJavaMany languages: C, C#, Python, Excel
LayersYour code, core API, driver manager, driverApplication, driver manager, driver, data source
NeedsA JDBC driver for your databaseAn ODBC driver and a data source on the computer
Connection detailsA JDBC address, user and passwordA data source name, or all the details written out
Safer queriesPrepared statementsPlaceholders (?)

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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Write 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.