JDBC(Java Database Connectivity)是一種Java API(應用程式介面),用於與關聯式資料庫系統進行交互。 它定義了一組Java 類和介面,使開發人員可以編寫Java應用程式,以便通過標準SQL語言與各種RDBMS進行通信。
下面是一個簡單的JDBC例子,使用JDBC API與MySQL數據庫進行交互:
import java.sql.*;
public class JDBCTest {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sample_db";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}
}
簡要解釋:
Class.forName()
DriverManager.getConnection()
連接到數據庫Connection.createStatement()
創建一個 Statement
對象,並使用它來執行SQL查詢ResultSet
對像來處理查詢結果String sql = "SELECT * FROM myTable WHERE datetime > ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setTimestamp(1, new Timestamp(date.getTime()));
其中,conn是已經建立好的數據庫連接對象,date是特定的日期對象。
String sql = "UPDATE myTable SET name = ?, age = ? WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 0; i < data.size(); i++) { //data為需要更新的數據
pstmt.setString(1, data.getName(i));
pstmt.setInt(2, data.getAge(i));
pstmt.setInt(3, data.getId(i));
pstmt.addBatch();
}
int[] result = pstmt.executeBatch();
其中,conn是已經建立好的數據庫連接對象。
String sql = "SELECT * FROM myTable LIMIT ? OFFSET ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pageSize);
pstmt.setInt(2, (pageNum - 1) * pageSize);
其中,pageSize表示每頁顯示的記錄數量,pageNum表示要查詢的頁碼。
Connection conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
try {
Statement stmt = conn.createStatement();
// some sql operations here
stmt.execute("INSERT INTO myTable(name, age) VALUES('Tom', 20)");
stmt.execute("UPDATE myTable SET age = 22 WHERE name = 'Tom'");
conn.commit();
} catch (SQLException e) {
conn.rollback();
} finally {
conn.setAutoCommit(true);
conn.close();
}
String sql = "SELECT t1.*, t2.age FROM table1 t1 JOIN table2 t2 ON t1.id = t2.table1Id";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age1 = rs.getInt("age1");
int age2 = rs.getInt("age2");
System.out.println(name + ", " + age1 + ", " + age2);
}
其中,t1和t2分別代表要關聯的兩張表,table1Id是t1這張表中用來關聯的id欄位名稱。