我在sqldevelop里直接写能把null值插进去:insert into testtb(id,fk,va)values(1,null,'fsdsf');但是在程序中用PreparedStatement的pstm.setInt(4, od.getSuid());就不能添加od.getSuid()这个null值,那么我该怎么解决这个呢??
自己看api setNull void setNull(int parameterIndex, int sqlType) throws SQLException Sets the designated parameter to SQL NULL. Note: You must specify the parameter's SQL type. Parameters: parameterIndex - the first parameter is 1, the second is 2, ... sqlType - the SQL type code defined in java.sql.Types Throws: SQLException - if parameterIndex does not correspond to a parameter er in the SQL statement; if a database access error occurs or this method is called on a closed PreparedStatement SQLFeatureNotSupportedException - if sqlType is a ARRAY, BLOB, CLOB, DATALINK, JAVA_OBJECT, NCHAR, NCLOB, NVARCHAR, LONGNVARCHAR, REF, ROWID, SQLXML or STRUCT data type and the JDBC driver does not support this data type第一个参数是parameter的位置,即的?的位置 第二个参数是parameter的类型,即你的字段的类型,你要设置个null,系统总要知道你的字段是什么类型吧。像setInt,setString什么的,方法名就限定了字段的类型了。
pstm.setInt(4, od.getSuid());?? 你有4个参数吗??
pstm.setInt(2, od.getSuid()); 应该是这样吧
insert into testtb(id,va)values(1,'fsdsf'); 如果fk可以是非空的话就可以了
if (od.getSuid == null) {
pstm.setNull(4, java.sql.Types.INTEGER, null);
} else {
pstm.setInt(4, od.getSuid());
}
setNull
void setNull(int parameterIndex,
int sqlType)
throws SQLException
Sets the designated parameter to SQL NULL.
Note: You must specify the parameter's SQL type.
Parameters:
parameterIndex - the first parameter is 1, the second is 2, ...
sqlType - the SQL type code defined in java.sql.Types
Throws:
SQLException - if parameterIndex does not correspond to a parameter er in the SQL statement; if a database access error occurs or this method is called on a closed PreparedStatement
SQLFeatureNotSupportedException - if sqlType is a ARRAY, BLOB, CLOB, DATALINK, JAVA_OBJECT, NCHAR, NCLOB, NVARCHAR, LONGNVARCHAR, REF, ROWID, SQLXML or STRUCT data type and the JDBC driver does not support this data type第一个参数是parameter的位置,即的?的位置
第二个参数是parameter的类型,即你的字段的类型,你要设置个null,系统总要知道你的字段是什么类型吧。像setInt,setString什么的,方法名就限定了字段的类型了。
你有4个参数吗??
应该是这样吧
如果fk可以是非空的话就可以了
我这还有个方法,就是也可以用setObject, 如下pstm.setObject(4, null, java.sql.Types.INTEGER);