JDBC(以mysql为例)

用于数据库访问的一套统一的API

主要的类:

  • DriverManager用于负责管理JDBC驱动程序。JDBC驱动必须加载注册后才能使用
  • SQLException 有关数据库操作的异常

接口:

  • Connection 数据库的连接对象
  • PreparedStatement 预编译的SQL语句对象
  • Statement 静态SQL语句的对象
  • ResultSet 数据库查询的结果集 

JDBC的使用步骤

  1.  载入JDBC驱动程序
    驱动名  mysql5:com.mysql.jdbc.Driver
                 mysql8:com.mysql.cj.jdbc.Driver
    加载注册驱动:Class.forName("com.mysql.jdbc.Driver");
  2. 定义连接的URL
    假设数据库的名字叫testdb,则mysql5的url的写法:
    jdbc:mysql://localhost:3306/testdb?useUnicode=true&autoReconnect=true
    mysql8的url:jdbc:mysql://localhost:3306/testdb?useSSL=false&useUnicode=true&autoReconnect=true&serverTimezone=GMT
  3. 建立连接
    使用getConnection方法:
    Connection DriverManager.getConnection(String url,String user,String pwd);
  4. 创建Statement对象(写具体的sql语句),现在常用PreparedStatement
    PrepareStatement conn.prepareStatement(sql);
    可以使用setXxxx(pos,value)将sql中对应的?传入实际的值
  5. 执行查询或DML操作
    execute()
    ResultSet executeQuery()//查询
    int excuteUpdate() //更新、删除、插入
  6. 结果处理 
    ResultSet对象的处理,假设对象名为rs
    while(rs.next()){
           //按照列的顺序来获取值,
            getXxx(int pos);//pos表示列的顺序,从1开始
            //按照列的名字
             getXxx(String columnName);//columnName表示列的名字
    }
  7. 关闭连接,释放资源(按顺序)
    1. ResultSet对象.close()
    2. Statement对象.close()
    3. Connection对象.close()

 

你可能感兴趣的:(JavaSE)