java中对数据库进行增删改查的代码
时间: 2024-04-28 10:24:40 浏览: 63
数据库增删改查
好的,以下是Java中对数据库进行增删改查的基本代码:
首先需要导入相关的包:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
```
1. 建立数据库连接:
```java
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // 加载数据库驱动
String url = "jdbc:mysql://localhost:3306/test"; // 数据库连接地址
String username = "root"; // 数据库用户名
String password = "123456"; // 数据库密码
conn = DriverManager.getConnection(url, username, password); // 建立数据库连接
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
```
2. 插入数据:
```java
String sql = "insert into user(name, age, gender, phone) values(?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 20);
pstmt.setString(3, "男");
pstmt.setString(4, "18888888888");
int row = pstmt.executeUpdate();
if (row > 0) {
System.out.println("插入成功!");
}
```
3. 删除数据:
```java
String sql = "delete from user where id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
int row = pstmt.executeUpdate();
if (row > 0) {
System.out.println("删除成功!");
}
```
4. 修改数据:
```java
String sql = "update user set age=? where id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 30);
pstmt.setInt(2, 1);
int row = pstmt.executeUpdate();
if (row > 0) {
System.out.println("修改成功!");
}
```
5. 查询数据:
```java
String sql = "select * from user";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
String phone = rs.getString("phone");
System.out.println("id:" + id + ",姓名:" + name + ",年龄:" + age + ",性别:" + gender + ",电话:" + phone);
}
```
需要注意的是,在使用完连接、预处理语句、结果集等资源之后,需要进行关闭操作,以释放资源:
```java
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
```
阅读全文