Java Connect to SQLite with JDBC Example
- Details
- Written by Nam Ha Minh
- Last Updated on 25 October 2020   |   Print Email
1. Download SQLite JDBC driver
You can download the latest version of JDBC driver for SQLite here. The download is categorized by versions, so browse a directory for a specific version you want: 3.5.9, 3.6.16, 3.7.2, etc. As of this writing, the latest version is 3.7.2 which corresponds to the jar file sqlite-jdbc-3.7.2.jar.Beside Java class files, the jar file includes SQLite binaries for Windows, Linux and Mac (for both 32-bit and 64-bit).Place the sqlite-jdbc-VERSION.jar into your classpath.
2. SQLite JDBC database connection URL
The SQLite JDBC driver can load a SQLite database from file system or creates one in memory.Here is the syntax of database connection URL for file system database:jdbc:sqlite:database_file_path
Where database_file_path can be either relative or absolute path. For example:jdbc:sqlite:product.db
jdbc:sqlite:C:/work/product.db
And here is the syntax of database connection URL for memory database:jdbc:sqlite::memory:
jdbc:sqlite:
3. Loading SQLite JDBC driver
Class.forName("org.sqlite.JDBC");Or:
DriverManager.registerDriver(new org.sqlite.JDBC());
4. Making SQLite JDBC connection
The following example program creates a connection to a SQLite database file product.db which is in the same directory as the program, prints some database metadata information, and closes the connection:package net.codejava.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.SQLException; /** * This program demonstrates making JDBC connection to a SQLite database. * @author www.codejava.net * */ public class JdbcSQLiteConnection { public static void main(String[] args) { try { Class.forName("org.sqlite.JDBC"); String dbURL = "jdbc:sqlite:product.db"; Connection conn = DriverManager.getConnection(dbURL); if (conn != null) { System.out.println("Connected to the database"); DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData(); System.out.println("Driver name: " + dm.getDriverName()); System.out.println("Driver version: " + dm.getDriverVersion()); System.out.println("Product name: " + dm.getDatabaseProductName()); System.out.println("Product version: " + dm.getDatabaseProductVersion()); conn.close(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } } }That's Java code example to establish connection to a SQLite database.To see the coding in action, I recommend you to watch the video below:
JDBC API References:
Related JDBC Tutorials:
- JDBC CRUD Tutorial
- JDBC Transaction Tutorial
- How to Read Database Meta Data in JDBC
- How to call stored procedure with JDBC
Comments