)完成JDBC的增删改查。
时间: 2024-03-27 10:37:17 浏览: 14
好的,以下是JDBC的增删改查示例代码:
1. 建立连接
```
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "root");
```
2. 增加数据
```
String sql = "insert into student(name, age, score) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 18);
pstmt.setInt(3, 90);
int result = pstmt.executeUpdate();
```
3. 删除数据
```
String sql = "delete from student where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
int result = pstmt.executeUpdate();
```
4. 修改数据
```
String sql = "update student set name = ?, age = ?, score = ? where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "李四");
pstmt.setInt(2, 20);
pstmt.setInt(3, 80);
pstmt.setInt(4, 2);
int result = pstmt.executeUpdate();
```
5. 查询数据
```
String sql = "select * from student";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
int score = rs.getInt("score");
System.out.println("id=" + id + ", name=" + name + ", age=" + age + ", score=" + score);
}
```
完整代码如下:
```
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 建立连接
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "root");
// 增加数据
String sql = "insert into student(name, age, score) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 18);
pstmt.setInt(3, 90);
int result = pstmt.executeUpdate();
// 删除数据
sql = "delete from student where id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
result = pstmt.executeUpdate();
// 修改数据
sql = "update student set name = ?, age = ?, score = ? where id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "李四");
pstmt.setInt(2, 20);
pstmt.setInt(3, 80);
pstmt.setInt(4, 2);
result = pstmt.executeUpdate();
// 查询数据
sql = "select * from student";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
int score = rs.getInt("score");
System.out.println("id=" + id + ", name=" + name + ", age=" + age + ", score=" + score);
}
// 关闭连接
rs.close();
stmt.close();
pstmt.close();
conn.close();
}
}
```
注意:在使用JDBC连接数据库时,需要保证连接的正确性和安全性,避免SQL注入等问题的出现。