zoukankan      html  css  js  c++  java
  • JDBC

    使用JDBC

    在maven项目中添加依赖

    mysql
    mysql-connector-java
    LATEST

    驱动Driver类建立链接执行sql语句
    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    
        try (
            Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                "root", "admin");
            Statement s = c.createStatement();             
        )
        {
            String sql = "insert into hero values(null," + "'提莫'" + "," + 313.0f + "," + 50 + ")";
            s.execute(sql);
    
    
    
            String sql = "select count(*) from hero";
    
            ResultSet rs = s.executeQuery(sql);
            int total = 0;
            while (rs.next()) {
                total = rs.getInt(1);
            }
    
            System.out.println("表Hero中总共有:" + total+" 条数据");
              
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    
        try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
            // 根据sql语句创建PreparedStatement
            PreparedStatement ps = c.prepareStatement(sql);
        ) {
             
            // 设置参数
            ps.setString(1, "提莫");
            ps.setFloat(2, 313.0f);
            ps.setInt(3, 50);
            // 执行
            ps.execute();
    
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    事务,mysql需使用inndb数据库类型

            c.setAutoCommit(false);
    
            // 加血的SQL
            String sql1 = "update hero set hp = hp +1 where id = 22";
            s.execute(sql1);
    
            // 减血的SQL
            // 不小心写错写成了 updata(而非update)
    
            String sql2 = "updata hero set hp = hp -1 where id = 22";
            s.execute(sql2);
    
            // 手动提交
            c.commit();
    

    参考资料:
    how2j教程

  • 相关阅读:
    iOS-Core-Animation-Advanced-Techniques(一)
    vue 路由
    Vue 生产环境部署
    vue 单文件组件
    vue 插件
    Vue 混合
    vue 自定义指令
    vue render函数 函数组件化
    vue render函数
    vue 过渡状态
  • 原文地址:https://www.cnblogs.com/bestefforts/p/11350030.html
Copyright © 2011-2022 走看看