zoukankan      html  css  js  c++  java
  • 数据库增删改查

    代码示例:

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

    运行截图:

  • 相关阅读:
    DataGridView 控件和 DataGrid 控件之间的区别
    winform 如何创建mdi属性IsMdiContainer=true
    窗体分为左右两部分,要求在左边栏点击按钮时,右边动态加载窗体
    OLEDBConnection 和SQLConnection 有什么区别
    成为一个顶级设计师的八大秘诀
    青春追梦
    四维领导力:明道、取势、优术、树人
    走好青春
    再贺开业
    骑车在暴雨中有感
  • 原文地址:https://www.cnblogs.com/zyj3955/p/13916625.html
Copyright © 2011-2022 走看看