Java 和 SQLite 連接選項
您正在尋找合適的驅動程式庫來將 Java 應用程式連接到 SQLite 資料庫。為了解決這個問題,我們提供了以下各種替代方案:
適用於SQLite 的Java JDBC 驅動程式
強烈推薦的選項是Java SQLite JDBC 驅動程式。透過將其 JAR 檔案包含在專案的類別路徑中並匯入 java.sql.*,您可以無縫連接到 SQLite 資料庫並與之互動。
示範其用法的範例應用程式是:
// Import necessary libraries import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class Test { public static void main(String[] args) throws Exception { // Load the SQLite JDBC driver Class.forName("org.sqlite.JDBC"); // Establish a connection to the database file Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db"); // Create a statement object Statement stat = conn.createStatement(); // Drop the 'people' table if it exists and create a new one stat.executeUpdate("drop table if exists people;"); stat.executeUpdate("create table people (name, occupation);"); // Prepare a SQL statement to insert data into the 'people' table PreparedStatement prep = conn.prepareStatement( "insert into people values (?, ?);"); // Insert data into the 'people' table prep.setString(1, "Gandhi"); prep.setString(2, "politics"); prep.addBatch(); prep.setString(1, "Turing"); prep.setString(2, "computers"); prep.addBatch(); prep.setString(1, "Wittgenstein"); prep.setString(2, "smartypants"); prep.addBatch(); // Execute the batch to add the records to the database conn.setAutoCommit(false); prep.executeBatch(); conn.setAutoCommit(true); // Retrieve data from the 'people' table ResultSet rs = stat.executeQuery("select * from people;"); while (rs.next()) { System.out.println("name = " + rs.getString("name")); System.out.println("job = " + rs.getString("occupation")); } // Close the ResultSet and Connection objects rs.close(); conn.close(); } }
其他SQLite JDBC 驅動程式
雖然提到的Java JDBC 驅動程式
以上是如何使用不同的 JDBC 驅動程式將 Java 應用程式連接到 SQLite 資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!