使用jdbc完成数据的增删改查代码
时间: 2023-12-08 07:04:34 浏览: 66
好的,下面是使用jdbc完成数据的增删改查的基础示例代码:
//导入需要的包和类
import java.sql.*;
import java.util.*;
//定义数据库连接信息
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=GMT%2B8";
String user = "root";
String password = "123456";
//建立数据库连接
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
//定义增删改查操作
Statement stmt = null;
ResultSet rs = null;
try {
//查询操作
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM user");
while (rs.next()) {
System.out.println(rs.getInt("id") + "," + rs.getString("name") + "," + rs.getInt("age"));
}
//插入操作
stmt.executeUpdate("INSERT INTO user VALUES (4, 'Tom', 20)");
//更新操作
stmt.executeUpdate("UPDATE user SET age = 30 WHERE name = 'Tom'");
//删除操作
stmt.executeUpdate("DELETE FROM user WHERE id = 4");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭数据库连接
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
希望能帮到您!
阅读全文