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教程

  • 相关阅读:
    刨析js代码执行机制
    H5离线缓存基础系列
    meta 详解
    如何成长为一名合格的web架构师?
    整理的互联网公司面试趋势
    http协议
    前端现在到底需要什么样的人才
    webpack 4.0 版本的简单使用
    vue的懒加载如何实现?
    Runtime的几个小例子(含Demo)
  • 原文地址:https://www.cnblogs.com/bestefforts/p/11350030.html
Copyright © 2011-2022 走看看