给我一个jdbc的增删改查案例
时间: 2024-04-02 20:11:50 浏览: 46
好的,下面是一个简单的 JDBC 增删改查案例:
首先,我们需要获取数据库连接。
```java
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库的地址
String username = "root"; // 数据库用户名
String password = "password"; // 数据库密码
try (Connection conn = DriverManager.getConnection(url, username, password)) {
System.out.println("数据库连接成功!");
// 后面可以进行增删改查的操作
} catch (SQLException e) {
System.out.println("数据库连接失败:" + e.getMessage());
}
}
}
```
接下来,我们可以进行增删改查的操作。
```java
// 插入数据
try (Statement stmt = conn.createStatement()) {
String sql = "INSERT INTO users (username, password, age) VALUES ('Tom', 'password123', 21)";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println("插入数据成功!影响了 " + rowsAffected + " 行数据。");
} catch (SQLException e) {
System.out.println("插入数据失败:" + e.getMessage());
}
// 更新数据
try (Statement stmt = conn.createStatement()) {
String sql = "UPDATE users SET age = 22 WHERE username = 'Tom'";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println("更新数据成功!影响了 " + rowsAffected + " 行数据。");
} catch (SQLException e) {
System.out.println("更新数据失败:" + e.getMessage());
}
// 删除数据
try (Statement stmt = conn.createStatement()) {
String sql = "DELETE FROM users WHERE username = 'Tom'";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println("删除数据成功!影响了 " + rowsAffected + " 行数据。");
} catch (SQLException e) {
System.out.println("删除数据失败:" + e.getMessage());
}
// 查询数据
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
int age = rs.getInt("age");
System.out.println("id: " + id + ", username: " + username + ", password: " + password + ", age: " + age);
}
} catch (SQLException e) {
System.out.println("查询数据失败:" + e.getMessage());
}
```
以上就是一个简单的 JDBC 增删改查案例。
阅读全文