jdbc的增删改查代码
时间: 2023-07-10 07:21:09 浏览: 105
jdbc增删改查
以下是Java JDBC实现数据库的增删改查代码示例:
1. 导入相关的包
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
```
2. 建立数据库连接
```java
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
```
3. 插入数据
```java
String sql = "INSERT INTO user(name, age) VALUES(?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "Tom");
ps.setInt(2, 20);
int count = ps.executeUpdate();
if (count > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
} catch (SQLException e) {
e.printStackTrace();
}
```
4. 更新数据
```java
String sql = "UPDATE user SET age=? WHERE name=?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 22);
ps.setString(2, "Tom");
int count = ps.executeUpdate();
if (count > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
} catch (SQLException e) {
e.printStackTrace();
}
```
5. 删除数据
```java
String sql = "DELETE FROM user WHERE name=?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "Tom");
int count = ps.executeUpdate();
if (count > 0) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
} catch (SQLException e) {
e.printStackTrace();
}
```
6. 查询数据
```java
String sql = "SELECT * FROM user";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(name + " " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
```
7. 关闭数据库连接
```java
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
```
阅读全文