如何使用 JDBC 程式連線到 SQLite 資料庫?


A. SQLite 是一個程序內庫,它實現了自包含的、無伺服器的、零配置的、事務性 SQL 資料庫引擎。它是一個數據庫,無需配置,這意味著與其他資料庫不同,您無需在系統中配置它。

SQLite 引擎不是像其他資料庫一樣的獨立程序,您可以根據需要將其靜態或動態連結到您的應用程式。SQLite 直接訪問其儲存檔案。

連線 SQLite 資料庫的 URL 為 jdbc:sqlite:test.db,連線它的驅動程式類名為 org.sqlite.JDBC

在繼續示例之前

  • 從 sqlite-jdbcrepository 下載最新版本的 sqlite-jdbc-(VERSION).jar。

  • 將下載的 jar 檔案 sqlite-jdbc-(VERSION).jar 新增到您的類路徑中,或者您可以將其與 -classpath 選項一起使用,如下面的示例所示。

示例

假設在 SQLite 資料庫中有一個名為 employee_data 的表,其中包含 4 條記錄,如下所示

ID      NAME       AGE    ADDRESS     SALARY
------- -------- ------- ---------- ----------
1        Paul       32   California   20000.0
2        Allen      25   Texas        15000.0
3        Teddy      23   Norway       20000.0
4        Mark       25   Richmond     65000.0

以下 JDBC 程式建立與 SQLite 資料庫的連線,檢索名為 employee_data 的表的內容並顯示它。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectToSQLite {
   public static void main(String[] args) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new org.sqlite.JDBC());
      //Getting the connection
      String url = "jdbc:sqlite:test.db";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Query to retrieve records
      String query = "Select * from employee_data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      System.out.println("Contents of the employee_data table:");
      while(rs.next()) {
         System.out.print("ID: "+rs.getInt("ID")+", ");
         System.out.print("Name: "+rs.getString("Name")+", ");
         System.out.print("Age: "+rs.getInt("Age")+", ");
         System.out.print("Salary: "+rs.getInt("Salary")+", ");
         System.out.print("Address: "+rs.getString("Address"));
         System.out.println();
      }
   }
}

輸出

Connections established......
Contents of the employee_data table:
ID: 1, Name: Paul, Age: 32, Salary: 20000, Address: California
ID: 2, Name: Allen, Age: 25, Salary: 15000, Address: Texas
ID: 3, Name: Teddy, Age: 23, Salary: 20000, Address: Norway
ID: 4, Name: Mark, Age: 25, Salary: 65000, Address: Rich-Mond

更新於: 2019-07-30

1K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告