重拾JDBC(二)通過Statement執行更新操作

通過Statement執行更新操作

    /**
     * 通過 JDBC 向指定的數據表中插入一條記錄. 
     * 
     * 1. Statement: 用於執行 SQL 語句的對象
     * 1). 通過 Connection 的 createStatement() 方法來獲取
     * 2). 通過 executeUpdate(sql) 可以執行 SQL 語句.
     * 3). 傳入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT
     * 
     * 2. Connection、Statement 都是應用程序和數據庫服務器的連接資源. 使用後一定要關閉.
     * 需要在 finally 中關閉 Connection 和 Statement 對象. 
     * 
     * 3. 關閉的順序是: 先關閉後獲取的. 即先關閉 Statement 後關閉 Connection
     */
    @Test
    public void testStatement() throws Exception{
        //1. 獲取數據庫連接
        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. 執行插入. 
            //1). 獲取操作 SQL 語句的 Statement 對象: 
            //調用 Connection 的 createStatement() 方法來獲取
            statement = conn.createStatement();

            //2). 調用 Statement 對象的 executeUpdate(sql) 執行 SQL 語句進行插入
            statement.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                //5. 關閉 Statement 對象.
                if(statement != null)
                    statement.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally{
                //2. 關閉連接
                if(conn != null)
                    conn.close();                           
            }
        }

    }


    public Connection getConnection2() throws Exception{
        //1. 準備連接數據庫的 4 個字符串. 
        //1). 創建 Properties 對象
        Properties properties = new Properties();

        //2). 獲取 jdbc.properties 對應的輸入流
        InputStream in = 
                this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");

        //3). 加載 2) 對應的輸入流
        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. 加載數據庫驅動程序(對應的 Driver 實現類中有註冊驅動的靜態代碼塊.)
        Class.forName(driver);

        //3. 通過 DriverManager 的 getConnection() 方法獲取數據庫連接. 
        return DriverManager.getConnection(jdbcUrl, user, password);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章