簡體   English   中英

在JDBC中編寫SQL查詢的最佳實踐是什么?

[英]What is the Best practice for writing a SQL query in JDBC

我正在通過使用JSP和使用JDBC的Servlet開發電子商務Web應用程序來學習Java Web Development。 我正在檢查GitHub,GoogleCode等中的一些項目,我遇到了一些代碼,我發現這些代碼在下面的界面中聲明選擇,更新,插入方法是不尋常的:

public interface DBDriver {

public void init( DBConnection connection );
public ResultSet selectQuery( String sqlStatement );
public int updateQuery( String sqlStatement );
public ResultSet select( String table, String[] fields, String where );
public ResultSet select( String table, String[] fields, String where, String[] join, String groupBy[], String having, String orderBy[], int start, int limit );
public int insert( String table, HashMap<String, String> fields );
public int update( String table, HashMap<String, String> fields, String where );
public int update( String table, HashMap<String, String> fields, String where, String orderBy[], int start, int limit );
public int delete( String table, String where );
public int delete( String table, String where, String orderBy[], int start, int limit );
public DBConnection getConnection();

}

並在另一個類中實現這些方法,例如:DBDriverSQL。

其中一種實現方法是:

public ResultSet select( String table, String[] fields, String where, String[] join, String groupBy[], String having, String orderBy[], int start, int limit ) {
    StringBuilder sql = new StringBuilder();

    /* Make sure a table is specified */
    if( table == null ) {
        throw new RuntimeException();
    }

    sql.append( "SELECT " );

    /* Empty field list means we'll select all fields */
    if( fields == null || fields.length < 1 ) {
        sql.append( "*" );
    }
    else {
        sql.append( Util.joinArray( fields, "," ) );
    }

    /* Add table and fields list to query */
    sql.append( " FROM " ).append( getFullTableName( table ) );

    /* Any JOINs?*/
    if( join != null && join.length > 0 ) {
        sql.append( " " ).append( Util.joinArray( join, " " ) );
    }

    /* Searching on a WHERE condition? */
    if( where != null && !where.isEmpty() ) {
        sql.append( " WHERE " ).append( where );
    }        

    /* Add GROUP BY clause */
    if( groupBy != null && groupBy.length > 0 ) {
        sql.append( Util.joinArray( groupBy, "," ) );
    }

    if( having != null && !having.isEmpty() ) {
        sql.append( " HAVING " ).append( having );
    }

    if( orderBy != null && orderBy.length > 0 ) {
        sql.append( " ORDER BY " ).append( Util.joinArray( orderBy, "," ) );
    }

    if( limit > 0 ) {
        if( start < 1 ) {
            start = 0;
        }

        sql.append( " LIMIT " ).append( start ).append( "," ).append( limit );
    }

    /* Return the compiled SQL code */
    return selectQuery( sql.toString() );
}

這些方法在控制器Servlet中調用,用於從數據庫中提取數據。 例:

String where = "listId = " + listId;
    String[] fields = { "b.*, l.listId, l.price, l.comment, l.listDate, l.active, l.condition, l.currency, u.*" };
    String[] join = { "INNER JOIN bzb.book b ON l.isbn=b.isbn",
                "INNER JOIN bzb.user u ON l.userId=u.userId" };
    ResultSet result = bzb.getDriver().select( "booklisting l", fields, where, join, null, null, null, 0, 1 );

我的問題是,與標准的JDBC程序相比,這種方法是否被認為是一種很好的做法,例如:

String sql = "select SetID,SetName,SetPrice,SetQuality from setdetails  where heroID = " + id;

        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            lists.add(new Set(rs.getInt("SetID"), rs.getString("SetName"), rs.getString("SetPrice"), rs.getString("SetQuality")));
        }
        return lists;

我建議你使用標准的JDBC方式(如果它足夠復雜和/或在項目的許多部分中使用,那么將SQL作為存儲過程移動到數據庫中)。 我使用連接編寫了幾個頁面的SQL語句,使用DBDriver方法看起來很難看。 我建議保持目標,即通過嘗試任何難以閱讀的編碼,使您的所有代碼都易於閱讀,這可以避免您輸入更多行。 一個簡單的論點是針對結構不良的代碼或丑陋的代碼來實現較小的性能提升。

請注意,許多SQL模板的目標是避免為每個SQL查詢反復編寫鍋爐代碼(try / catch / finally / handle exception)。 您提供的示例不會這樣做。 它只能幫助您構建sql語句。

我建議你使用try / catch / finally塊,你可以按照你創建它們的相反順序關閉finally塊中的connection,preparedStatement和resultSet(在關閉它們之前先檢查它們是否為null)。

如果拋出SQLException,請捕獲它,將導致問題的記錄的主鍵值(用於記錄目的)添加到SQLException,然后重新拋出它。

使用PreparedStament ,傳遞原始參數沒有意義。 我會做一些小修改,以使其更符合Preparedstatement

String sql = "select SetID,SetName,SetPrice,SetQuality from setdetails  where heroID = ?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,intVal); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM