To read data from a SQLite database using Java, you can use the JDBC driver provided by the SQLite project. Here’s an example code snippet that demonstrates how to read data from a SQLite database using Java:
import java.sql.*; public class SQLiteDataReader { public static void main(String[] args) { // Database URL String url = "jdbc:sqlite:/path/to/your/database.sqlite"; // SQL query String query = "SELECT * FROM your_table"; try { // Register JDBC driver Class.forName("org.sqlite.JDBC"); // Open a connection Connection conn = DriverManager.getConnection(url); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery(query); // Process the result set while (rs.next()) { // Retrieve the data by column name int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); // Do something with the data System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("--------------------------"); } // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
Replace /path/to/your/database.sqlite
with the actual path to your SQLite database file.
Make sure to have the SQLite JDBC driver (e.g., sqlite-jdbc-*.jar
) included in your classpath. You can download the driver from the official SQLite website or include it as a Maven/Gradle dependency.
The code connects to the SQLite database, creates a statement, and executes the query using executeQuery()
. The result set is then processed using while (rs.next())
loop to retrieve data from each row. Finally, it closes the resources to free up memory.
Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.