1. 什么是JDBC?
JDBC(Java Database Connectivity)是一個Java API,用于連接和執行SQL陳述句與關系型資料庫進行互動,JDBC提供了一組介面和類,使Java程式能夠與各種資料庫通信,如MySQL、Oracle、PostgreSQL等,
2. JDBC的主要組件
JDBC主要由以下幾個組件組成:
DriverManager:負責加載資料庫驅動,并建立與資料庫的連接,Connection:表示與資料庫的連接,Statement:用于執行SQL陳述句,PreparedStatement:用于執行預編譯的SQL陳述句,ResultSet:表示查詢結果集,
3. 連接資料庫
在連接資料庫之前,需要確保已經安裝了相應的資料庫驅動并將其添加到專案中,以下是一個簡單示例,演示如何使用JDBC連接到MySQL資料庫:
java
Copy
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcConnectExample {
public static void main(String[] args) {
try {
// 加載資料庫驅動
Class.forName("com.mysql.cj.jdbc.Driver");
// 連接到資料庫
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected to database!");
// 關閉連接
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 執行SQL查詢
要使用JDBC執行SQL查詢,可以創建一個Statement物件,然后呼叫其executeQuery()方法,以下是一個簡單示例,演示如何查詢資料庫中的資料:
java
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcQueryExample {
public static void main(String[] args) {
try {
// 加載資料庫驅動并連接到資料庫
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
// 創建Statement物件并執行SQL查詢
Statement statement = connection.createStatement();
String sql = "SELECT id, name FROM users";
ResultSet resultSet = statement.executeQuery(sql);
// 處理結果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 關閉資源
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. 執行SQL更新
要使用JDBC執行SQL更新(如插入、更新或洗掉),可以創建一個Statement物件,然后呼叫其executeUpdate()方法,以下是一個簡單示例,演示如何向資料庫中插入資料:
java
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JdbcUpdateExample {
public static void main(String[] args) {
try {
// 加載資料庫驅動并連接到資料庫
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
// 創建Statement物件并執行SQL更新
Statement statement = connection.createStatement();
String sql = "INSERT INTO users (name, age) VALUES ('John Doe', 30)";
int rowsAffected = statement.executeUpdate(sql);
System.out.println("Rows affected: " + rowsAffected);
// 關閉資源
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
**6. 使用PreparedStatement**
`PreparedStatement`是一個預編譯的`Statement`物件,可以提高SQL陳述句的執行效率,它還可以防止SQL注入攻擊,以下是一個簡單示例,演示如何使用`PreparedStatement`插入資料:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JdbcPreparedStatementExample {
public static void main(String[] args) {
try {
// 加載資料庫驅動并連接到資料庫
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
// 創建PreparedStatement物件并執行SQL更新
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "Jane Doe");
preparedStatement.setInt(2, 28);
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);
// 關閉資源
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
7. 事務處理
事務是一組邏輯操作單元,執行這些操作要么全部成功,要么全部失敗,在JDBC中,可以使用Connection物件的commit()和rollback()方法進行事務處理,以下是一個簡單示例,演示如何使用事務處理:
java
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JdbcTransactionExample {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 加載資料庫驅動并連接到資料庫
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
connection = DriverManager.getConnection(url, username, password);
// 關閉自動提交(開啟事務)
connection.setAutoCommit(false);
// 執行SQL更新
String sql = "UPDATE users SET age = age + 1 WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.executeUpdate();
// 提交事務
connection.commit();
System.out.println("Transaction committed.");
} catch (Exception e) {
// 回滾事務
try {
if (connection != null) {
connection.rollback();
System.out.println("Transaction rolled back.");
}
} catch (Exception ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
// 關閉資源
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
8. 關閉資源
在JDBC中,需要確保及時關閉資源,如Connection、Statement和ResultSet等,可以使用close()方法或者Java 7中引入的try-with-resources陳述句進行資源關閉,以下是一個簡單示例,演示如何使用try-with-resources關閉資源:
java
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcCloseResourceExample {
public static void main(String[] args) {
try {
// 加載資料庫驅動
Class.forName("com.mysql.cj.jdbc.Driver");
// 連接到資料庫
String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "mypassword";
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()) {
// 執行SQL查詢并處理結果集
推薦閱讀:
https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA
https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/554227.html
標籤:其他
上一篇:IPC橫向移動
下一篇:返回列表
