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

posted on 2019-08-14 09:47  Best_Efforts  阅读(102)  评论(0编辑  收藏  举报

导航