java中連結資料庫的具體操作以及pstmt.setObject(i+1, objects[i])這行代碼的意思

來源:互聯網
上載者:User

標籤:

package dao; import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet; public class BaseDao {    private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";    private String url = "jdbc:sqlserver://localhost:1433;databaseName=EasyBuy";     private String user = "sa";    private String password = "sa";     /**     * 擷取資料庫連接對象     *      * @return     */    public Connection getcConnection() {        Connection conn = null;        try {            Class.forName(driver);            conn = DriverManager.getConnection(url, user, password);        } catch (Exception e) {            e.printStackTrace();        }        return conn;    }    /**     * 關閉資料庫連接對象     * @param rs     * @param pstmt     * @param conn     */    public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn){        try {            if(rs!=null){                rs.close();            }            if(pstmt!=null){                pstmt.close();            }            if(conn!=null){                conn.close();            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 增刪改方法     * @param sql     * @param objects     * @return     */    public int executeUpdate(String sql,Object[] objects){             int num=0;             PreparedStatement pstmt=null;              Connection conn=getcConnection();             try {                pstmt=conn.prepareStatement(sql);                for (int i = 0; i < objects.length; i++) {                    pstmt.setObject(i+1,objects[i]);                 }                num=pstmt.executeUpdate();            } catch (Exception e) {                e.printStackTrace();            }finally{                closeAll(null, pstmt, conn);            }             return num;    }}

上述是java串連資料庫的具體步驟,關閉資料庫的話,肯定是先關查詢結果rs,再關閉pstmt,再關閉conn而開啟反之~~,這裡的三個對像應該是建立串連,建立查詢,和查詢結果。
要想清楚是先有串連,再建立查詢,才會返回結果。

對於pstmt.setObject(i+1, objects[i]);這行代碼,因為在方法引用了可變參數(為什麼要引用可變參數,是因為前面是字串,後面是資料庫語句,類型不符),所謂可變參數就是:適用於參數個數不確定,類型不確定的情況,java把可變參數當做數組處理,但不是數組,功能比數組強,可以變成沒有參數,或者為空白。而這行代碼就是將資料庫語句賦值給參數,因為參數是從1開始的,故要寫成i+1.

java中連結資料庫的具體操作以及pstmt.setObject(i+1, objects[i])這行代碼的意思

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.