java增删改查源代码
时间: 2024-07-05 20:01:07 浏览: 93
C#操作Excel增删改查源代码+截图.rar
5星 · 资源好评率100%
在Java中,数据库操作通常使用JDBC(Java Database Connectivity)API,这是一个标准接口,用于连接、操作数据库。以下是一个简单的示例,展示了如何使用JDBC执行基本的增删改查操作:
**插入(Insert):**
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public void insertData(String sql, Object... args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
```
**删除(Delete):**
```java
public void deleteData(String sql, Object... args) {
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
```
**更新(Update):**
```java
public void updateData(String sql, Object... args) {
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < args.length; i += 2) {
pstmt.setObject(i, args[i]);
pstmt.setObject(i + 1, args[i + 1]);
}
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
```
**查询(Select):**
```java
public ResultSet fetchData(String sql, Object... args) {
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
return pstmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
```
这里假设`ResultSet`是一个`java.sql.ResultSet`对象,用于处理查询结果。
阅读全文