java web-06-jdbc

JDBC:java连接数据库

需要jar包的支持:

  • mysql-conneter-java (连接驱动,必须要导入)

1、JDBC固定步骤

  1. 加载驱动;
  2. 连接数据库,代表数据库
  3. 向数据库发送SQL的对象Statement : CRUD
  4. 编写SQL
  5. 执行SQL
  6. 关闭连接,释放资源,先开后关
public class JDBCTest01 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //useUnicode=true&characterEncoding=utf-8:解决中文乱码
        String url = "jdbc:mysql://localhost:3306/zichuang1?useSSL=true&useUnicode=true&characterEncoding=utf-8";
        String username = "***";
        String password = "***";

        //1、加载驱动;
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2、连接数据库,代表数据库;Connection:连接
        //DriverManager管理一组 JDBC 驱动程序的基本服务。
        //加载 Driver 类并在 DriverManager 类中注册后,它们即可用来与数据库建立连接。
        // 当调用 DriverManager.getConnection 方法发出连接请求时,DriverManager 将检查每
        // 个驱动程序,查看它是否可以建立连接。
        Connection connection = DriverManager.getConnection(url,username,password);
        //3、向数据库发送SQL的对象Statement
        Statement statement = connection.createStatement();
        //PreparedStatement安全的;ResultSet普通的
        //4、编写SQL
        String sql = "select * from people";//查询数据
        //String sql = "delete from people where id=3";
        //受影响的行数,增删改都是使用executeUpdate即可!executeUpdate:执行更新
        //int i = statement.executeUpdate(sql);
        //5、执行查询SQL,返回一个ResultSet结果集;executeQuery:执行查询
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id:"+resultSet.getObject("id"));
            System.out.println("name:"+resultSet.getObject("name"));
            System.out.println("age:"+resultSet.getObject("age"));
            System.out.println("address:"+resultSet.getObject("address"));
        }
        //6、关闭连接,释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

2、预编译SQL

public class JDBCTest02 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/zichuang1?useUnicode=true&characterEncoding=utf-8";
        String username = "***";
        String password = "***";
        //1、加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2、连接数据库
        Connection connection = DriverManager.getConnection(url,username,password);
        //3、编写SQL
        String sql = "insert into people(id,name,age,address) values(?,?,?,?)";
        //4、预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,7);
        preparedStatement.setString(2,"张三");
        preparedStatement.setInt(3,20);
        preparedStatement.setString(4,"北京");
        //preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
        //5、执行SQL
        int i = preparedStatement.executeUpdate();
        if (i>0){
            System.out.println("插入成功");
        }
        //6、关闭连接
        preparedStatement.close();
        connection.close();
    }
}

3、事务

要么都成功,要么都失败

public class JDBCTest03 {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/zichuang1?useUnicode=true&characterEncoding=utf-8";
        String username = "***";
        String password = "***";
        Connection connection = null;
        try{
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、连接数据库
            connection = DriverManager.getConnection(url,username,password);
            //3、通知数据库开启事务,false 开启;如果没写,事务错了也会执行完毕,但没有回滚
            //setAutoCommit:设置自动提交
            connection.setAutoCommit(false);
            String sql = "update account set money = money+100 where name='A'";
            //prepareStatement准备声明;executeUpdate执行查询
            connection.prepareStatement(sql).executeUpdate();
            //制造错误
            //int i = 1/0;
            String sql2 = "update account set money = money-100 where name='B'";
            connection.prepareStatement(sql2).executeUpdate();
            connection.commit();//以上两条SQL都执行成功了,就提交事务
            System.out.println("success");
        } catch (Exception e) {
            try{
                //如果出现异常,就通知数据库回滚事务 rollback回降
                connection.rollback();
            } catch (SQLException e1){
                //printStackTrace:打印堆栈跟踪
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {//finally:最后
            try{
                connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

    }
}
posted @ 2021-10-11 21:01  比特风  阅读(30)  评论(0)    收藏  举报