JDBC使用过程

DriverManager:驱动管理类

主要作用

一、注册驱动

  实际开发中注册驱动会使用如下的方式:

  Class.forName("com.mysql.jdbc.Driver");

  因为之前的方式会导致驱动注册两次。

二、获得连接

  Connection getConnection(String url,String username,String password);

  url写法:jdbc:mysql://localhost:3306/jdbc

  jdbc:协议

  mysql:子协议

  localhost:主机名

  3306:端口号

  url简写:jdbc:mysql:///jdbc

Connection:连接对象

主要作用:

一、创建执行SQL语句的对象

  Statement createSatement():执行SQL语句,有SQL注入的漏洞存在。

  PreparedStatement prepareStatement(String sql):预编译SQL语句,解决SQL注入的漏洞。

  CallableStatement prepareCall(String sql):执行SQL中存储过程

二、进行事务的管理

  setAutoCommit(boolean autoCommit):设置事务是否自动提交。

  commit():事务提交

  rollback():事务回滚

Statement:执行SQL

主要作用:

  一、执行SQL语句

    boolean execute(String sql):执行SQL,执行select语句返回true,否则返回false

    ResultSet executeQuery(String sql):执行SQL中的select语句

    int executeUpdate(String sql):执行SQL中的insert/update/delete语句

  二、执行批处理操作

    addBatch(String sql):添加到批处理

    executeBatch():执行批处理

    clearBatch():清空批处理

ResultSet:结果集

结果集:其实就是查询语句(select)语句查询结果的封装。

主要作用:

  结果集获取查询到的结果的。

  next():针对不同的类型的数据可以使用getXXX()获取数据,通用的获取数据的方法:

getObject();

使用JDBC的例子:

public void demo4(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try{
            // 注册驱动:
            Class.forName("com.mysql.jdbc.Driver");
            // 获得连接:
            conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "abc");
            // 创建执行SQL语句的对象:
            stmt = conn.createStatement();
            // 编写SQL:
            String sql = "select * from user";
            // 执行SQL:
            rs = stmt.executeQuery(sql);
            // 遍历结果集:
            while(rs.next()){
                System.out.println(rs.getInt("uid")+"   "+rs.getString("username")+"   "+rs.getString("password")+"    "+rs.getString("name"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            // 释放资源
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                rs = null;   //垃圾回收机制,使其更快被回收
            }
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stmt = null;
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/shouyaya/p/12315291.html