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 can SQLite and ZFS be used together for software development?
- How do I use the SQLite ZIP VFS to compress a database?
- How do I use SQLite with Zephyr?
- How can I use SQLite with Python?
- How do I extract the year from a datetime value in SQLite?
- How do I use the SQLite SELECT statement?
- How can I use SQLite with Kubernetes?
- How do I use the SQLite YEAR function?
- How can I use SQLite with Xamarin Forms?
- How do I use SQLite transactions?
See more codes...