sqliteHow can I use SQLite with Java?
SQLite is a popular open source SQL database engine that is used for storing structured data in mobile devices, web browsers, and operating systems. It can be used with Java through the SQLite JDBC driver.
The following example code shows how to connect to an SQLite database, create a table, insert data into the table, and query the table:
// Load the SQLite JDBC driver
Class.forName("org.sqlite.JDBC");
// Connect to the database
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
// Create the table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER)");
// Insert data
statement.executeUpdate("INSERT INTO people VALUES ('John', 30)");
statement.executeUpdate("INSERT INTO people VALUES ('Jane', 25)");
// Query the table
ResultSet results = statement.executeQuery("SELECT * FROM people");
while (results.next()) {
System.out.println("Name: " + results.getString("name"));
System.out.println("Age: " + results.getInt("age"));
}
Output example
Name: John
Age: 30
Name: Jane
Age: 25
The code above consists of the following parts:
- Load the SQLite JDBC driver: The
Class.forName
method is used to load the SQLite JDBC driver. - Connect to the database: The
DriverManager.getConnection
method is used to connect to the database. - Create the table: The
executeUpdate
method is used to create the table. - Insert data: The
executeUpdate
method is used to insert data into the table. - Query the table: The
executeQuery
method is used to query the table. - Process the result: The
next
andgetXXX
methods are used to process the result.
For more information, please refer to the SQLite JDBC Driver and SQLite Java Tutorial.
More of Sqlite
- How do I use the SQLite ZIP VFS to compress a database?
- How to configure SQLite with XAMPP on Windows?
- How do I format an SQLite database with version 3?
- How can I use SQLite with Python?
- How do I import data from a SQLite zip file?
- How can I resolve the error "no such table" when using SQLite?
- How do I extract the year from a datetime value in SQLite?
- How can I use SQLite to query for records between two specific dates?
- How do I use SQLite to retrieve data from a specific year?
- How do I generate XML output from a SQLite database?
See more codes...