zoukankan      html  css  js  c++  java
  • 12、JDBC 流程

    JDBC:Java Data Base Connection

    JDBC是用于运行sql语句并从数据库中获取新新的java API.

    JDBC是用来(让我们的程序)通过网络来操作数据库的,作用非常重要;JDBC技术也是Java核心技术之中的一个。

    是使用JDBC驱动程序訪问数据库的首选方式

    通过JDBC操作数据库——步骤:

      第1步:注冊驱动 (仅仅做一次)

      第2步:建立连接(Connection)

      第3步:创建运行SQL的语句(Statement)

      第4步:运行语句

      第5步:处理运行结果(ResultSet)

      第6步:释放资源

    使用JDBC第一步:载入驱动

      注冊驱动有三种方式:

      1.      Class.forName(“com.mysql.jdbc.Driver”);

               推荐这样的方式,不会对详细的驱动类产生依赖

      2. DriverManager.registerDriver(com.mysql.jdbc.Driver);

               会对详细的驱动类产生依赖

      3. System.setProperty(“jdbc.drivers”, “driver1:driver2”);

               尽管不会对详细的驱动类产生依赖;但注冊不太方便。所以非常少使用

    使用JDBC第二步:建立连接

      通过Connection建立连接,Connection是一个接口类。其功能是与数据库进行连接(会话)。

      建立Connection接口类对象:

      Connection conn =DriverManager.getConnection(url, user, password);

      当中URL的格式要求为:

      JDBC:子协议:子名称//主机名:port/数据库名?属性名=属性值&…

      如:"jdbc:mysql://localhost:3306/test“

      user即为登录数据库的username,如root

      password即为登录数据库的密码,为空就填””

    使用JDBC第三步:创建运行对象

      运行对象Statement负责运行SQL语句。由Connection对象产生。

      Statement st = connection.createStatement();

      Statement接口类还派生出两个接口类PreparedStatement和CallableStatement,这两个接口类对象为我们提供了更加强大的数据訪问功能。

      PreparedStatement能够对SQL语句进行预编译,这样防止了   SQL注入 提高了安全性。

      PreparedStatement  ps=connection.prepareStatement( "update user set id=? where username=?”); ————sql语句中庸 ? 作为通配符,变量值通过参数设入:ps.setObject(1, object);

      而且预编译结果能够存储在PreparedStatement对象中。当多次运行SQL语句时能够提高效率。

      作为Statement的子类,PreparedStatement继承了Statement的全部函数。

      CallableStatement接口

      CallableStatement类继承了PreparedStatement类,他主要用于运行SQL存储过程。

      在JDBC中运行SQL存储过程须要转义。

      JDBC API提供了一个SQL存储过程的转义语法:

      {call<procedure-name>[<arg1>,<arg2>, ...]}

      procedure-name:是所要运行的SQL存储过程的名字

      [<arg1>,<arg2>, ...]:是相相应的SQL存储过程所须要的參数

    使用JDBC第四步:运行SQL语句

      运行对象Statement 或 PreparedStatement 提供两个经常使用的方法来运行SQL语句。

      executeQuery(Stringsql),该方法用于运行实现查询功能的sql语句。返回类型为ResultSet(结果集)。

      如:ResultSet  rs =st.executeQuery(sql);

      executeUpdate(Stringsql),该方法用于运行实现增、删、改功能的sql语句,返回类型为int,即受影响的行数。

      如:int flag = st.executeUpdate(sql);

    使用JDBC第五步:处理运行结果

      ResultSet对象

      ResultSet对象负责保存Statement运行后所产生的查询结果。

      结果集ResultSet是通过游标来操作的。

      游标就是一个可控制的、能够指向随意一条记录的指针。

      有了这个指针我们就能轻易地指出我们要对结果集中的哪一条记录进行改动、删除,或者要在哪一条记录之前插入数据。一个结果集对象中仅仅包括一个游标。

       另外,借助ResultSetMetaData ,可以将数据表的结构信息都查出来。

      ResultSetMetaData rsmd= resultSet.getMetaData();

    使用JDBC 第六步——释放资源

      复制代码

    /**
     * Created by Clear on 2018/8/11.
     * here provide the kind of connections from mysql database,and close the resources of the mysql
     * there are
     *      load driver
     *      use properties file
     *      use xml file
     *      use tomcat
     *      and... so on
     *
     *
     *
     */
    public class MysqlUtil {
        /**
         * 链接数据库
         */
        /**
         * 方法一:
         * 加载驱动的方法不止一种,但这种最常用
          */
        public static Connection getConnectionOne(String database,String username,String password){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+database,username,
                        password);
                return connection;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 方法二:
         * 利用properties文件
         * ::::: 在Web 编程时 文件难以定位
          */
        public static Connection getConnectionTwo() {
            /**
             * 建立文件
             */
            Properties pro = new Properties();
    
            InputStream in = MysqlUtil.class.getClassLoader().getResourceAsStream("mysqllog.properties");
            try {
                pro.load(in);
                Class.forName(pro.getProperty("driver"));
                String username = pro.getProperty("user");
                String password = pro.getProperty("password");
                String database = pro.getProperty("database");
                String url = pro.getProperty("url");
    
                Connection connection = DriverManager.getConnection(url+database,username,password);
                return connection;
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
        // Connection ,Statement, ResultSet 这几个资源的关闭是有顺序的
        public static void close (Object...objects) throws MysqlCloseException {
            Map<String,Object> map = new HashMap();
            for(Object o : objects){
                if(o instanceof ResultSet){
                    map.put("ResultSet",o);
                }else if(o instanceof Connection){
                    map.put("Connection",o);
                }else if(o instanceof Statement){
                    map.put("Statement",o);
                }else if(o instanceof PreparedStatement){
                    map.put("PreparedStatement",o);
                }else{
                    throw new MysqlCloseException("关闭异常,不能处理");
                }
            }
            Object obj = map.get("ResultSet");
            if(obj!=null){
                ResultSet r = (ResultSet)obj;
                try {
                    r.close();
                    map.remove("ResultSet");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            obj = map.get("PreparedStatement");
            if(obj!=null){
                PreparedStatement p = (PreparedStatement)obj;
                try {
                    p.close();
                    map.remove("PreparedStatement");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            obj = map.get("Statement");
            if(obj!=null){
                Statement s = (Statement)obj;
                try {
                    s.close();
                    map.remove("Statement");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            obj = map.get("Connection");
            if(obj!=null){
                Connection c = (Connection)obj;
                try{
                    c.close();
                    map.remove("Connection");
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }

      数据库资源不关闭,其占用的内存不会被释放,徒耗资源,影响系统。

  • 相关阅读:
    Codeforces 992C(数学)
    Codeforces 990C (思维)
    Codeforces 989C (构造)
    POJ 1511 Invitation Cards(链式前向星,dij,反向建边)
    Codeforces 1335E2 Three Blocks Palindrome (hard version)(暴力)
    POJ 3273 Monthly Expense(二分)
    POJ 2566 Bound Found(尺取前缀和)
    POJ 1321 棋盘问题(dfs)
    HDU 1506 Largest Rectangle in a Histogram(单调栈)
    POJ 2823 Sliding Window(单调队列)
  • 原文地址:https://www.cnblogs.com/chenxiaoxian/p/10426196.html
Copyright © 2011-2022 走看看