設定 PreparedStatement 的引數
需要使用 set*方法設定查詢字串中的佔位符:
String sql = "SELECT * FROM EMP WHERE JOB = ? AND SAL > ?";
//Create statement to make your operations
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "MANAGER"); // String value
statement.setInt(2, 2850); // int value
特別案例
設定 NULL 值:
使用例如 setInt 和 setLong 方法無法設定空值,因為這些方法使用原始型別(int 和 long)而不是物件(Integer 和 Long),並且會導致 NullPointerException 被丟擲:
void setFloat(int parameterIndex, float x)
void setInt(int parameterIndex, int x)
void setLong(int parameterIndex, long x)
這些案例可以使用 setNull 來處理。
setNull(int parameterIndex, int sqlType)
它是鍵入的,因此必須提供第二個引數,請參閱 java.sql.Types
//setting a NULL for an integer value
statement.setNull(2, java.sql.Types.INTEGER);
設定 LOB
LOB 需要使用特殊物件。
Clob longContent = connection.createClob();
Writer longContentWriter = longContent.setCharacterStream(1); // position: beginning
longContentWriter.write("This will be the content of the CLOB");
pstmt = connection.prepareStatement("INSERT INTO CLOB_TABLE(CLOB_VALUE) VALUES (?)");
pstmt.setClob(1, longContent);
關於 set*方法的例外情況
SQLException- 如果parameterIndex與 SQL 語句中的引數標記不對應; 如果發生資料庫訪問錯誤或在關閉的PreparedStatement上呼叫此方法
SQLFeatureNotSupportedException- 如果 sqlType 是ARRAY,BLOB,CLOB,DATALINK,JAVA_OBJECT,NCHAR,NCLOB,NVARCHAR,LONGNVARCHAR,REF,ROWID,SQLXML或STRUCT資料型別且 JDBC 驅動程式不支援此資料型別