麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

java攻城獅之路--復(fù)習(xí)JDBC

2019-11-14 20:58:27
字體:
供稿:網(wǎng)友
java攻城獅之路--復(fù)習(xí)JDBC1、JDBC中如何獲取數(shù)據(jù)庫鏈接Connection?

Driver 是一個接口: 數(shù)據(jù)庫廠商必須提供實現(xiàn)的接口. 能從其中獲取數(shù)據(jù)庫連接.

可以通過 Driver 的實現(xiàn)類對象獲取數(shù)據(jù)庫連接.

1. 加入 MySQL 驅(qū)動

1). 解壓 mysql-connector-java-5.1.7.zip

2). 在當前項目下新建 lib 目錄

3). 把 mysql-connector-java-5.1.7-bin.jar 復(fù)制到 lib 目錄下

4). 右鍵 build-path , add to buildpath 加入到類路徑下.s

幾種常用數(shù)據(jù)庫的JDBC URL:

@Testpublic void testDriver() throws SQLException {    //1. 創(chuàng)建一個 Driver 實現(xiàn)類的對象    Driver driver = new com.mysql.jdbc.Driver();    //2. 準備連接數(shù)據(jù)庫的基本信息: url, user, passWord    String url = "jdbc:mysql://localhost:3306/test";    PRoperties info = new Properties();    info.put("user", "root");    info.put("password", "1230");    //3. 調(diào)用 Driver 接口的 connect(url, info) 獲取數(shù)據(jù)庫連接    Connection connection = driver.connect(url, info);    System.out.println(connection);}
獲取數(shù)據(jù)庫鏈接最簡單方法
/**JDBC.properties文件中的內(nèi)容:#driver=Oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl#user=scott#password=javadriver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/atguiguuser=rootpassword=1230*/public Connection getConnection() throws Exception{    String driverClass = null;    String jdbcUrl = null;    String user = null;    String password = null;    //讀取類路徑下的 jdbc.properties 文件    InputStream in =             getClass().getClassLoader().getResourceAsStream("jdbc.properties");    Properties properties = new Properties();    properties.load(in);    driverClass = properties.getProperty("driver");    jdbcUrl = properties.getProperty("jdbcUrl");    user = properties.getProperty("user");    password = properties.getProperty("password");    //通過反射常見 Driver 對象.     Driver driver =             (Driver) Class.forName(driverClass).newInstance();    Properties info = new Properties();    info.put("user", user);    info.put("password", password);    //通過 Driver 的 connect 方法獲取數(shù)據(jù)庫連接.     Connection connection = driver.connect(jdbcUrl, info);    return connection;    }    @Test    public void testGetConnection() throws Exception{        System.out.println(getConnection());    }
在不修改源程序的情況下,獲取任何數(shù)據(jù)庫鏈接的通用方法(原始方法)

解決方案: 把數(shù)據(jù)庫驅(qū)動 Driver 實現(xiàn)類的全類名、url、user、password 放入一個

配置文件中, 通過修改配置文件的方式實現(xiàn)和具體的數(shù)據(jù)庫解耦.

    @Test    public void testDriverManager() throws SQLException, IOException {        String driverClass = null;        String jdbcUrl = null;        String user = null;        String password = null;        InputStream in = getClass().getClassLoader().getResourceAsStream(                "jdbc.properties");        Properties proper = new Properties();        proper.load(in);        driverClass = proper.getProperty("driver");        jdbcUrl = proper.getProperty("jdbcUrl");        user = proper.getProperty("user");        password = proper.getProperty("password");        Connection connection = DriverManager.getConnection(jdbcUrl, user,                password);        System.out.println(connection);    }
使用DriverManager獲取數(shù)據(jù)庫鏈接的方法
    @Test    public void testDriverManager() throws ClassNotFoundException, SQLException {        String driverClass = "com.mysql.jdbc.Driver";        // String driverClass2 = "oracle.jdbc.driver.OracleDriver";        String jdbcUrl = "jdbc:mysql://localhost:3306/test";        // String jdbcUrl2 = "jdbc:oracle:thin:@localhost:1521:orcl";        String user = "root";        // String user2 = "scott";        String password = "123";        // String password2 = "tiger";        Class.forName(driverClass);        Connection connection = DriverManager.getConnection(jdbcUrl, user,                password);        System.out.println(connection);    }
更為簡便的使用DriverManager獲取數(shù)據(jù)庫鏈接的方法
 1 @Test 2 public void testGetConnection2() throws Exception{ 3         System.out.println(getConnection2());  4 } 5      6 public Connection getConnection2() throws Exception{ 7         //1. 準備連接數(shù)據(jù)庫的 4 個字符串.  8         //1). 創(chuàng)建 Properties 對象 9         Properties properties = new Properties();10         11         //2). 獲取 jdbc.properties 對應(yīng)的輸入流12         InputStream in = 13                 this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");14         15         //3). 加載 2) 對應(yīng)的輸入流16         properties.load(in);17         18         //4). 具體決定 user, password 等4 個字符串. 19         String user = properties.getProperty("user");20         String password = properties.getProperty("password");21         String jdbcUrl = properties.getProperty("jdbcUrl");22         String driver = properties.getProperty("driver");23         24         //2. 加載數(shù)據(jù)庫驅(qū)動程序(對應(yīng)的 Driver 實現(xiàn)類中有注冊驅(qū)動的靜態(tài)代碼塊.)25         Class.forName(driver);26         27         //3. 通過 DriverManager 的 getConnection() 方法獲取數(shù)據(jù)庫連接. 28         return DriverManager.getConnection(jdbcUrl, user, password);29 }
獲取數(shù)據(jù)庫連接的最終版本,既解耦又利用到了DriverManager

2、如何通過 JDBC 向指定的數(shù)據(jù)表中插入一條記錄?1. Statement: 用于執(zhí)行 SQL 語句的對象1). 通過 Connection 的 createStatement() 方法來獲取2). 通過 executeUpdate(sql) 可以執(zhí)行 SQL 語句.3). 傳入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT2. Connection、Statement 都是應(yīng)用程序和數(shù)據(jù)庫服務(wù)器的連接資源. 使用后一定要關(guān)閉. 需要在 finally 中關(guān)閉 Connection 和 Statement 對象. 3. 關(guān)閉的順序是: 先關(guān)閉后獲取的. 即先關(guān)閉 Statement 后關(guān)閉 Connection.

    @Test    public void testStatement() throws Exception{        //1. 獲取數(shù)據(jù)庫連接        Connection conn = null;        Statement statement = null;                try {            conn = getConnection2();                        //3. 準備插入的 SQL 語句            String sql = null;            //            sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +//                    "VALUES('XYZ', '[email protected]', '1990-12-12')";//            sql = "DELETE FROM customers WHERE id = 1";            sql = "UPDATE customers SET name = 'TOM' " +                    "WHERE id = 4";            System.out.println(sql);                        //4. 執(zhí)行插入.             //1). 獲取操作 SQL 語句的 Statement 對象:             //調(diào)用 Connection 的 createStatement() 方法來獲取            statement = conn.createStatement();                        //2). 調(diào)用 Statement 對象的 executeUpdate(sql) 執(zhí)行 SQL 語句進行插入            statement.executeUpdate(sql);        } catch (Exception e) {            e.printStackTrace();        } finally{            try {                //5. 關(guān)閉 Statement 對象.                if(statement != null)                    statement.close();            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            } finally{                //2. 關(guān)閉連接                if(conn != null)                    conn.close();                                        }        }            }
通過Statement獲取連接,執(zhí)行更新操作(包括insert,update,delete
    public void update(String sql){        Connection conn = null;        Statement statement = null;        String sql = null;        try {            conn = JDBCTools.getConnection();            statement = conn.createStatement();            statement.executeUpdate(sql);        } catch (Exception e) {            e.printStackTrace();        } finally{            JDBCTools.release(statement, conn);        }    }
通用的更新的方法: 包括 INSERT、UPDATE、DELETE(即是要建立一個數(shù)據(jù)庫工具類:獲取數(shù)據(jù)庫連接,關(guān)閉連接)
package com.shellway.jdbc;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/** * 操作 JDBC 的工具類. 其中封裝了一些工具方法 Version 1 */public class JDBCTools {    public static void release(ResultSet rs,             Statement statement, Connection conn) {        if(rs != null){            try {                rs.close();            } catch (SQLException e) {                e.printStackTrace();            }        }                if (statement != null) {            try {                statement.close();            } catch (Exception e2) {                e2.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();            } catch (Exception e2) {                e2.printStackTrace();            }        }    }        /**     * 關(guān)閉 Statement 和 Connection     * @param statement     * @param conn     */    public static void release(Statement statement, Connection conn) {        if (statement != null) {            try {                statement.close();            } catch (Exception e2) {                e2.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();            } catch (Exception e2) {                e2.printStackTrace();            }        }    }    /**     * 1. 獲取連接的方法. 通過讀取配置文件從數(shù)據(jù)庫服務(wù)器獲取一個連接.     *      * @return     * @throws Exception     */    public static Connection getConnection() throws Exception {        // 1. 準備連接數(shù)據(jù)庫的 4 個字符串.        // 1). 創(chuàng)建 Properties 對象        Properties properties = new Properties();        // 2). 獲取 jdbc.properties 對應(yīng)的輸入流        InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream(                "jdbc.properties");        // 3). 加載 2) 對應(yīng)的輸入流        properties.load(in);        // 4). 具體決定 user, password 等4 個字符串.        String user = properties.getProperty("user");        String password = properties.getProperty("password");        String jdbcUrl = properties.getProperty("jdbcUrl");        String driver = properties.getProperty("driver");        // 2. 加載數(shù)據(jù)庫驅(qū)動程序(對應(yīng)的 Driver 實現(xiàn)類中有注冊驅(qū)動的靜態(tài)代碼塊.)        Class.forName(driver);        // 3. 通過 DriverManager 的 getConnection() 方法獲取數(shù)據(jù)庫連接.        return DriverManager.getConnection(jdbcUrl, user, password);    }}
附上:要建立的數(shù)據(jù)庫工具類:JDBCTools

3、總結(jié):

1、Connection:代表應(yīng)用程序和數(shù)據(jù)庫的一個連接.

2、Statement:是用于操作 SQL 的對象.

3、ResultSet:封裝 JDBC 的查詢結(jié)果.

package com.shellway.jdbc;import java.io.IOException;import java.io.InputStream;import java.security.interfaces.RSAKey;import java.sql.Connection;import java.sql.Date;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;import org.junit.Test;public class ReviewTest {        /**     * 1. ResultSet 封裝 JDBC 的查詢結(jié)果.     */    @Test    public void testResultSet(){                Connection connection = null;        Statement statement = null;        ResultSet resultSet = null;                try {            //1. 獲取數(shù)據(jù)庫連接            connection = getConnection();                        //2. 調(diào)用 Connection 對象的 createStatement() 方法獲取 Statement 對象            statement = connection.createStatement();                        //3. 準備 SQL 語句            String sql = "SELECT id, name, email, birth FROM customers";                        //4. 發(fā)送 SQL 語句: 調(diào)用 Statement 對象的  executeQuery(sql) 方法.            //得到結(jié)果集對象 ResultSet            resultSet = statement.executeQuery(sql);                        //5. 處理結(jié)果集:            //5.1 調(diào)用 ResultSet 的 next() 方法: 查看結(jié)果集的下一條記錄是否有效,             //若有效則下移指針            while(resultSet.next()){                //5.2 getXxx() 方法獲取具體的列的值.                 int id = resultSet.getInt(1);                String name = resultSet.getString(2);                String email = resultSet.getString(3);                Date birth = resultSet.getDate(4);                                System.out.println(id);                System.out.println(name);                System.out.println(email);                System.out.println(birth);                                System.out.println();            }                    } catch (Exception e) {            e.printStackTrace();        } finally{            //6. 關(guān)閉數(shù)據(jù)庫資源            releaseDB(resultSet, statement, connection);        }    }        /**     * 1. Statement 是用于操作 SQL 的對象     */    @Test    public void testStatement(){        Connection connection = null;        Statement statement = null;                try {            //1. 獲取數(shù)據(jù)庫連接            connection = getConnection();                        //2. 調(diào)用 Connection 對象的 createStatement() 方法獲取 Statement 對象            statement = connection.createStatement();                        //3. 準備 SQL 語句            String sql = "UPDATE customers SET name = 'Jerry' " +                    "WHERE id = 5";                        //4. 發(fā)送 SQL 語句: 調(diào)用 Statement 對象的  executeUpdate(sql) 方法            statement.executeUpdate(sql);                    } catch (Exception e) {            e.printStackTrace();        } finally{            //5. 關(guān)閉數(shù)據(jù)庫資源: 由里向外關(guān)閉.             releaseDB(null, statement, connection);        }                }        public void releaseDB(ResultSet resultSet, Statement statement,            Connection connection){                if(resultSet != null){            try {                resultSet.close();            } catch (SQLException e) {                e.printStackTrace();            }        }                if(statement != null){            try {                statement.close();            } catch (SQLException e) {                e.printStackTrace();            }        }                if(connection != null){            try {                connection.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }        @Test    public void testGetConnection2() throws Exception{                Connection connection = getConnection();                System.out.println(connection);     }    public Connection getConnection() throws IOException,            ClassNotFoundException, SQLException {        //0. 讀取 jdbc.properties        /**         * 1). 屬性文件對應(yīng) Java 中的 Properties 類         * 2). 可以使用類加載器加載 bin 目錄(類路徑下)的文件         */        Properties properties = new Properties();        InputStream inStream = ReviewTest.class.getClassLoader()                .getResourceAsStream("jdbc.properties");        properties.load(inStream);                //1. 準備獲取連接的 4 個字符串: user, password, jdbcUrl, driverClass        String user = properties.getProperty("user");        String password = properties.getProperty("password");        String jdbcUrl = properties.getProperty("jdbcUrl");        String driverClass = properties.getProperty("driverClass");                //2. 加載驅(qū)動: Class.forName(driverClass)        Class.forName(driverClass);                //3. 調(diào)用         //DriverManager.getConnection(jdbcUrl, user, password)        //獲取數(shù)據(jù)庫連接        Connection connection = DriverManager                    .getConnection(jdbcUrl, user, password);        return connection;    }        /**     * Connection 代表應(yīng)用程序和數(shù)據(jù)庫的一個連接.     * @throws Exception      */    @Test    public void testGetConnection() throws Exception{        //1. 準備獲取連接的 4 個字符串: user, password, jdbcUrl, driverClass        String user = "root";        String password = "123";        String jdbcUrl = "jdbc:mysql:///test";        String driverClass = "com.mysql.jdbc.Driver";                //2. 加載驅(qū)動: Class.forName(driverClass)        Class.forName(driverClass);                //3. 調(diào)用         //DriverManager.getConnection(jdbcUrl, user, password)        //獲取數(shù)據(jù)庫連接        Connection connection = DriverManager                    .getConnection(jdbcUrl, user, password);                System.out.println(connection);     }}
總復(fù)習(xí)(包括獲取與數(shù)據(jù)庫的連接Connection,然后創(chuàng)建Statement,最后得到結(jié)果集ResultSet)

jdbc.properties文件內(nèi)容:

user=rootpassword=123driverClass=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/test

#user=scott#password=tiger#driverClass=oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl

吾時而躬身自省,自省使知已之不足,知不足而奮起,未為晚也!


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 久色免费 | 亚洲欧美国产精品va在线观看 | 成人短视频在线观看免费 | 一区二区三区欧美日韩 | 欧美黄色三级视频 | 欧美重口另类videos人妖 | 在线观看精品视频 | 国产一区二区三区视频观看 | 免费毛片随便看 | 91超在线| 日韩色电影 | 欧美亚州 | 成人福利视频网站 | 日本人乱人乱亲乱色视频观看 | 欧美精品一区二区久久 | 国产亚洲精品久久午夜玫瑰园 | 久久久久久久久久久久久九 | av免费在线观 | 亚洲第一精品在线 | 久久久久97国产精 | 久草视频福利在线观看 | 麻豆一二区 | 黄色av网站在线观看 | 欧美一级性 | 国产视频在线免费观看 | 国产免费专区 | 色婷婷tv | 日韩毛片网 | 在线观看91精品 | 免费看毛片的网站 | 91av在线免费 | 成人一级毛片 | 羞羞视频免费视频欧美 | 国产网站黄 | www.99久 | 一本色道久久综合狠狠躁篇适合什么人看 | av资源在线天堂 | 午夜精品久久久久久久99热浪潮 | 国产精品自拍啪啪 | 亚洲视频综合 | 久久精品亚洲一区 |