問題描述:
連接數據庫,執行SQL語句是必不可少的,下面給出了三種執行不通SQL語句的方法。
1.簡單的Statement執行SQL語句。有SQL注入,一般不使用。
public static void testStatement() throws Exception{
Statement stm = null;
ResultSet rs = null;
DataBaseConn con = new DataBaseConn();
try{
stm = con.getMssqlConn().createStatement();
rs = stm.executeQuery("select top 1 * from tfixitem");
if(rs.next()){
System.out.println("testStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE"));
}
con.closeCon();
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
2.防止SQL注入的PreparedStatement執行SQL語句。
public static void testPreparedStatement(){ PreparedStatement pstm = null; ResultSet rs = null; DataBaseConn con = new DataBaseConn(); try{ pstm = con.getMssqlConn().prepareStatement("select * from tfixitem where fixitem_id = ?"); pstm.setInt(1, 2); rs = pstm.executeQuery(); if(rs.next()){ System.out.println("testPreparedStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE")); } }catch(Exception e){ e.printStackTrace(); } }
3.執行存儲過程的CallableStatement執行存儲過程SQL
public static void testCallableStatement(){ CallableStatement cstm = null; ResultSet rs = null; DataBaseConn con = new DataBaseConn(); try{ cstm = con.getMssqlConn().prepareCall("{call SP_QUERY_TFIXITEM(?,?,?,?,?,?,?,?)}"); cstm.setInt(1, 2); cstm.setInt(2, 1); cstm.setInt(3, 0); cstm.setInt(4, 0); cstm.setString(5, ""); cstm.setString(6, ""); cstm.setString(7, ""); cstm.setInt(8, 0); rs = cstm.executeQuery(); if(rs.next()){ System.out.println("testCallableStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE")); } }catch(Exception e){ e.printStackTrace(); } }
總結:執行簡單SQL一般用preparedStatement,執行存儲過程使用CallableStatement
