隐藏页面特效

数据库增删改查

代码示例:

 

import java.sql.*;

 

public class Renewal { // 创建类
static Connection con; // 声明Connection对象
static PreparedStatement sql; // 声明PreparedStatement对象
static ResultSet res; // 声明ResultSet对象

 

public Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=GMT","root","020714");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}

 

public static void main(String[] args) {
Renewal c = new Renewal(); // 创建本类对象
con = c.getConnection(); // 调用连接数据库方法
try {
sql = con.prepareStatement("select * from tb_stu"); // 查询数据库
res = sql.executeQuery(); // 执行SQL语句
System.out.println("执行增加、修改、删除前数据:");
while (res.next()) {
String id = res.getString(1);
String name = res.getString("name");
String sex = res.getString("sex");
String birthday = res.getString("birthday"); // 遍历查询结果集
System.out.print("编号:" + id);
System.out.print(" 姓名:" + name);
System.out.print(" 性别:" + sex);
System.out.println(" 生日:" + birthday);
}
sql = con.prepareStatement("insert into tb_stu(name,sex,birthday) values(?,?,?)");
sql.setString(1, "阿杰"); // 预处理添加数据
sql.setString(2, "男");
sql.setString(3, "2001-03-08");
sql.executeUpdate();
sql = con.prepareStatement("update tb_stu set birthday "
+ "= ? where id = ? ");
sql.setString(1, "2012-12-02"); // 更新数据
sql.setInt(2, 1); // 更新数据
sql.executeUpdate();
Statement stmt = con.createStatement();
stmt.executeUpdate("delete from tb_stu where id = 9");//删除
// 查询修改数据后的tb_stu表中数据
sql = con.prepareStatement("select * from tb_stu");
res = sql.executeQuery(); // 执行SQL语句
System.out.println("执行增加、修改、删除后的数据:");
while (res.next()) {
String id = res.getString(1);
String name = res.getString("name");
String sex = res.getString("sex");
String birthday = res.getString("birthday");
System.out.print("编号:" + id);
System.out.print(" 姓名:" + name);
System.out.print(" 性别:" + sex);
System.out.println(" 生日:" + birthday);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行截图:

 

 


__EOF__

本文作者CherriesOvO
本文链接https://www.cnblogs.com/zyj3955/p/13916625.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   CherriesOvO  阅读(85)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示