How to Connect to SQLite via JDBC
SQLite is a small and fast file-based SQL database that is cross-platform and used on everything from phones to desktop computers.
There are a few JDBC driver implementations available for SQLite that allow users to connect to SQLite via JDBC in their Java programs. The JDBC driver that we will use in this article to connect to SQLite is an open-source driver provided by xerial.org. The driver can be downloaded from the following:
https://bitbucket.org/xerial/sqlite-jdbc/downloads/
Everything necessary to connect to SQLite over JDBC is provided in the downloaded .jar file.
To connect to SQLite via JDBC, the class name of the driver is required. For the xerial.org driver, the class name is the following:
org.sqlite.JDBC
In addition to the class name, a JDBC URL needs constructed to connect to an SQLite database. Listed below are examples of JDBC URLs to use with the xerial.org SQLite JDBC driver.
SQLite Driver JDBC URL Formats
Connect to an SQLite database file named demo.db located in the C:\Data directory on the user's local machine:
jdbc:sqlite:C:\Data\demo.db
Connect to an SQLite database file named demo.db in the C:\Data directory on the user's local machine with foreign key support enabled:
jdbc:sqlite:C:\Data\demo.db?foreign_keys=true
Sample Code for Making a JDBC Connection
Below is sample Java code for using the xerial.org SQLite driver to make a connection to an SQLite database.
Class dbDriver = Class.forName("org.sqlite.JDBC");
String jdbcURL = "jdbc:sqlite:C:\\Data\\demo.db?foreign_keys=true";
Connection connection = DriverManager.getConnection(jdbcURL);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from employee");
while(rs.next())
{
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
.
.
.
MySQL: How to Connect to MySQL via JDBC
Microsoft SQL Server: How to Connect to MS SQL Server via JDBC
Oracle: How to Connect to Oracle via JDBC
PostgreSQL: How to Connect to PostgreSQL via JDBC
Redshift: How to Connect to Redshift via JDBC