• 数据库增删改查


    代码示例:

    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();
    }
    }
    }

    运行截图:

  • 相关阅读:
    榫卯游戏介绍
    如果你有一个域名,你也可以免费有一个diy@yourdomain.com的企业邮局
    封装一个axios请求后台的通用方法
    javascript判断两个对象属性以及值是否相等
    遍历出文档内所有元素的tagName
    windows下nginx的安装及使用方法入门
    css样式重置样式
    canvas绘图
    表单脚本
    javascript事件
  • 原文地址:https://www.cnblogs.com/zyj3955/p/13916625.html
Copyright © 2020-2023  润新知