用java实现数据库的增删改查
时间: 2023-09-11 20:12:26 浏览: 89
数据库的增删改查可以通过 JDBC 技术实现,以下是 Java 代码示例:
先定义一个数据库连接的工具类 `DBUtil`:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
然后,我们可以通过以下 Java 代码实现数据库的增删改查:
```java
import java.sql.*;
public class CRUD {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获取数据库连接
conn = DBUtil.getConnection();
// 插入数据
String sqlInsert = "INSERT INTO user(name, age) VALUES (?, ?)";
pstmt = conn.prepareStatement(sqlInsert);
pstmt.setString(1, "Tom");
pstmt.setInt(2, 20);
int resultInsert = pstmt.executeUpdate();
System.out.println("插入数据的行数:" + resultInsert);
// 查询数据
String sqlSelect = "SELECT * FROM user WHERE age > ?";
pstmt = conn.prepareStatement(sqlSelect);
pstmt.setInt(1, 18);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("姓名:" + rs.getString("name") + ",年龄:" + rs.getInt("age"));
}
// 更新数据
String sqlUpdate = "UPDATE user SET age = ? WHERE name = ?";
pstmt = conn.prepareStatement(sqlUpdate);
pstmt.setInt(1, 21);
pstmt.setString(2, "Tom");
int resultUpdate = pstmt.executeUpdate();
System.out.println("更新数据的行数:" + resultUpdate);
// 删除数据
String sqlDelete = "DELETE FROM user WHERE age = ?";
pstmt = conn.prepareStatement(sqlDelete);
pstmt.setInt(1, 20);
int resultDelete = pstmt.executeUpdate();
System.out.println("删除数据的行数:" + resultDelete);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
运行程序后,可以看到插入数据、查询数据、更新数据和删除数据的结果。需要注意的是,这里的 SQL 语句以及表名、列名等信息都需要根据实际情况修改。
阅读全文