分別介紹:
①、PreparedStatement:
PreparedStatement是用來執行SQL查詢語句的API之一,用於執行參數化查詢;是java.sql包下面的一個接口,用來執行SQL語句查詢,通過調用connection.preparedStatement(sql)方法可以獲得PreparedStatment對象。數據庫系統會對sql語句進行預編譯處理(如果JDBC驅動支持的話),預處理語句將被預先編譯好,這條預編譯的sql查詢語句能在將來的查詢中重用,這樣一來,它比Statement對象生成的查詢速度更快。下面是一個例子:
public class PreparedStmtExample {
public static void main(String args[]) throws SQLException {
Connection conn = DriverManager.getConnection("數據庫地址", "名字", "密碼");
PreparedStatement preStatement = conn.prepareStatement("select distinct loan_type from loan where bank=?");
preStatement.setString(1, "Citibank");
ResultSet result = preStatement.executeQuery();
while(result.next()){
System.out.println("Loan Type: " + result.getString("loan_type"));
}
}
}
②、Statement:
用於通用查詢,不可以傳遞動態參數,(不建議使用)下面是一個例子:
Connection connection = DriverManager.getConnection("數據庫地址", "名字", "密碼");
//檢查數據是否存
String strSql1 = "SELECT COUNT(*) count FROM user_authentication WHERE user_id = 1 AND status = 3";
Statement statement =connection.createStatement();
ResultSet resultSet = statement.executeQuery(strSql1);
int row = 0;
f(resultSet.next())
{
row = resultSet.getInt("count");
}
③、CallableStatement:
是用於存儲過程,下面是一個例子:(未驗證)
Connection connection = DriverManager.getConnection("數據庫地址", "名字", "密碼");
CallableStatement cstmt = connection.prepareCall("{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
cstmt.executeQuery();
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2, 3);
上面是網上的案例,我一般是這麼調用的:
ZpmsStoredProcedure storedProcedure = new ZpmsStoredProcedure(getDataSource());
storedProcedure.setSql("ypl_ht_review_realname");//存儲過程名字
storedProcedure.declareParameter(new SqlParameter("userId",Types.INTEGER));//輸入參數
storedProcedure.declareParameter(new SqlParameter("stateCode",Types.INTEGER));
storedProcedure.declareParameter(new SqlOutParameter("result", Types.INTEGER));//輸出參數
Map<String, Object> out = storedProcedure.execute(map);//執行
int result = Integer.parseInt(String.valueOf(out.get("result")));//得到輸出參數
----------------------------------------------下面是上面用的封裝類------------------------------------------------------------
ZpmsStoredProcedure:
import javax.sql.DataSource;
import org.springframework.jdbc.object.StoredProcedure;
public class ZpmsStoredProcedure extends StoredProcedure {
public ZpmsStoredProcedure(DataSource dataSource){
super();
super.setDataSource(dataSource);
}
}
getDataSource()由來:
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcCallOperations;
public abstract class AbstractDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getDataSource() {
return dataSource;
}
protected SimpleJdbcCallOperations getSimpleJdbcCall() {
return new SimpleJdbcCall(dataSource);
}
}