Java連接SQLite數據庫
要使用java程序連接SQLite,並與SQLite進行數據存取操作,必須在系統上設置SQLite JDBC驅動程序和安裝Java JDK。按照以下步驟進行:
- 從sqlite-jdbc存儲庫下載最新版本的
sqlite-jdbc-(VERSION).jar
。 - 將下載的jar文件添加到類路徑。
- 使用java連接到SQLite數據庫。
1. 連接到SQLite數據庫
打開Eclipse IDE,創建一個JAVA工程:JavaWithSQLite,下載所需的sqlite-jdbc-(VERSION).jar
(下載地址:http://bitbucket.org/xerial/sqlite-jdbc/downloads/ 或者 http://mvnrepository.com/artifact/org.xerial/sqlite-jdbc/3.18.0 ),並將它放入到項目的類庫中。
使用以下代碼使用Java編程語言連接到SQLite數據庫,首先創建一個類:ConnectSQLite.java
,其代碼如下所示 -
package com.yiibai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectSQLite {
/**
* Connect to a sample database
*/
public static void connect() {
Connection conn = null;
try {
// db parameters
String url = "jdbc:sqlite:D:/software/sqlite/java-sqlite.db";
// create a connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
connect();
}
}
執行上面代碼後,應該會創建一個文件:D:/software/sqlite/java-sqlite.db
,並與數據庫java-sqlite.db
連接。
使用java創建數據庫
還可以使用java編程語言在SQLite中創建一個新的數據庫。假設要使用Java來創建一個名爲java_sqlite.db的數據庫。創建一個公共類:CreateDB.java
並使用以下代碼:
package com.yiibai;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CreateDB {
public static void createNewDatabase(String fileName) {
String url = "jdbc:sqlite:" + fileName;
try {
Connection conn = DriverManager.getConnection(url);
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
createNewDatabase("D:/software/sqlite/create-db.db");
}
}
執行上面代碼,得到以下結果 -
The driver name is SQLiteJDBC
A new database has been created.
現在創建一個名爲「create-db.db
」的新數據庫。可以看到對應創建目錄有一個文件:create-db.db
存在。
使用java創建一個表
假設要通過Java程序在SQLite中創建一個名爲tb_emp
的表,tb_emp
表具有id
,name
和capacity
這三列。首先創建一個Java類:CreateTable.java
,並使用以下代碼:
package com.yiibai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
public static void createNewTable() {
// SQLite connection string
String url = "jdbc:sqlite:D:/software/sqlite/java-sqlite.db";
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS employees (\n" + " id integer PRIMARY KEY,\n"
+ " name text NOT NULL,\n" + " capacity real\n" + ");";
try {
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
stmt.execute(sql);
System.out.println("Create table finished.");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
createNewTable();
}
}
執行上面代碼,得到以下結果 -
Create table finished.
執行上面代碼後,將在java-sqlite.db
數據庫中創建一個名稱爲:employees
的表。
向表中插入記錄
創建表後,使用以下代碼在表中插入一些記錄。 創建一個新的Java類:InsertRecords
,具有以下代碼:
package com.yiibai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertRecords {
private Connection connect() {
// SQLite connection string
String url = "jdbc:sqlite:D:/software/sqlite/java-sqlite.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void insert(String name, double capacity) {
String sql = "INSERT INTO employees(name, capacity) VALUES(?,?)";
try {
Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setDouble(2, capacity);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
InsertRecords app = new InsertRecords();
// insert three new rows
app.insert("Maxsu", 30000);
app.insert("Minsu", 40000);
app.insert("Miswong", 50000);
System.out.println("Insert data finished.");
}
}
現在記錄被插入到表中。 可以使用SELECT
命令查看它:
sqlite> .open java-sqlite.db
sqlite> .tables
employees
sqlite> select * from employees;
id,name,capacity
1,Maxsu,30000.0
2,Minsu,40000.0
3,Miswong,50000.0
sqlite>
sqlite>
查詢/選擇記錄
要使用Java程序從表中選擇/查詢記錄,請使用以下代碼。 創建一個新的Java類 - SelectRecords.java
,使用以下代碼 -
package com.yiibai;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectRecords {
private Connection connect() {
// SQLite connection string
String url = "jdbc:sqlite:D:/software/sqlite/java-sqlite.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void selectAll() {
String sql = "SELECT * FROM employees";
try {
Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// loop through the result set
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getDouble("capacity"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
SelectRecords app = new SelectRecords();
app.selectAll();
}
}
執行上面代碼,得到以下結果 -
注意: 因爲都是通過使用相同的編程過程,所以您可自己編寫其它數據庫操作,比如:更新和刪除表中的數據等等。