JDBC操作技巧

2021-06-11 18:19:51 字數 1702 閱讀 7319

對於純jdbc連線資料庫連線工具如下:

public static final string dbdriver="com.microsoft.sqlserver.jdbc.sqlserverdriver";

public static final string dburl="jdbc:sqlserver:";

public static final string dbusernamw="sa";

public static final string dbpsd="1111111";

private connection conn=null;

public databaseconnection()catch(exception e)

}public connection getconnection()

public void close() throws sqlexception

}

然後我們便是採用preparedstatement對sql語句進行預處理,如下:

preparedstatement pstm = null;

string sql = "insert into person(username,password) values(?,?)";

try

} catch (exception e) finally catch (exception e)

}

這是我們最常用的一種操作方式,可是問題就來了,我們所要操作的,必須對sql中的字段很明確,比如我們按條件來查詢的時候,我們就必須對條件的字段很清楚,可是,當資料庫字段增多的時候,我們所要查詢的條件規則很多,是不是每乙個條件,我們就要寫乙個方法呢?顯然,這種是直接的思維,然而這樣思維卻增加了很多**的冗餘,又或者說是,每次變換條件或者新增條件的時候,我們都必須對方法進行修改,甚至是增加。於是乎,我們想有沒有一種方式可以傳遞欄位名稱進去查詢,如where ?=?

本人親測,這種方式是不存在的,因為預處理欄位的時候,preparedstatement會自動在字串上加引號,那此時就不能達到我們想要的效果(如想要的是where name=? 得到的卻是 where 'name'=?),本人曾經在這樣的問題上糾結了很久。最終找到一種破解的方式,這裡借鑑了ibatis的map傳參方式。希望同行愛好者,我們除了要學會使用框架或外掛程式,得找個時間去研究一下它的原理(原始碼)哦。

對於where ?=? 顯然是不可取,但是對於字串佔位就可以的。例子如下:

public listfindbyparams(mapparams)

throws exception

string sql = string.format(

"select userid,username,password from person where %s=?", key);

pstm = this.conn.preparestatement(sql);

pstm.setobject(1, value);

resultset rs = pstm.executequery();

while(rs.next())

rs.close();

pstm.close();

return list;

}

哈哈 此種方式可以替代where ?=?,參照ibatis

JDBC基本操作

jdbc基本操作 載入驅動 class.forname com.mysql.jdbc.driver newinstance 建立連線 string url jdbc mysql localhost 3306 testdb?user root password root useunicode true...

JDBC操作(總結)

1.在專案中新建資料夾config 配置 在其中新建配置檔案db.properties drivername oracle.jdbc.driver.oracledriver url jdbc oracle thin localhost 1521 orcl username scott passwor...

JDBC優化技巧之一

以下是一些常用的jdbc小技巧,也許可以提高你的系統的執行速度。1.當使用preparedstatement callablestatement時,盡量使用它提供的setparams的方法。下面是錯誤的方法 callablestatement cstmt conn.preparecall resul...