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.forNamemethod is used to load the SQLite JDBC driver. - Connect to the database: The
DriverManager.getConnectionmethod is used to connect to the database. - Create the table: The
executeUpdatemethod is used to create the table. - Insert data: The
executeUpdatemethod is used to insert data into the table. - Query the table: The
executeQuerymethod is used to query the table. - Process the result: The
nextandgetXXXmethods 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 do I use SQLite with Zephyr?
- How do I call sqlitepcl.raw.setprovider() when using SQLite?
- How do I extract the year from a datetime value in SQLite?
- How do I use UUIDs in SQLite?
- How can I adjust the text size in SQLite?
- How can I resolve the error "no such table" when using SQLite?
- How can I use SQLite with Zabbix?
- How can I use SQLite to query for records between two specific dates?
- How do I set up an ODBC driver to connect to an SQLite database?
See more codes...