if(article.getAttribut() == null ) {
preparedStatement = initialisationRequetePreparee(connexion,
SQL_INSERT, true, article.getProduit().getId(), null ,
article.getDesignationArticle(), article.getArticleParent().getId());
} else {
preparedStatement = initialisationRequetePreparee(connexion,
SQL_INSERT, true, article.getProduit().getId(), article
.getAttribut().getId(),
article.getDesignationArticle(), article.getArticleParent().getId());
}
我的问题是如何在article.getAttribut().getId()
上设置null
,因为我收到了此错误
Caused by: java.sql.SQLException: Parameter index out of range (4 > number of parameters, which is 3).
PreparedStatement initialisationRequetePreparee方法
public static PreparedStatement initialisationRequetePreparee( Connection connexion, String sql, boolean returnGeneratedKeys, Object... objets ) throws SQLException {
PreparedStatement preparedStatement = connexion.prepareStatement( sql, returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS );
for ( int i = 0; i < objets.length; i++ ) {
preparedStatement.setObject( i + 1, objets[i] );
}
return preparedStatement;
}
答案 0 :(得分:0)
在PreparedStatement
中有一个方法
void setNull(int parameterIndex, int sqlType) throws SQLException
您可以使用该方法将值设置为null
注意:您的错误不同。与如何将值设置为null
无关,而与您需要设置的参数数量相关。
您的参数似乎少于您尝试设置的实际值的数量!参数的数量等于查询中存在的?
的数量。您的查询可能只有3个问号,而您正在设置第4个(不存在)值。
如果SQL_INSERT
为article.getAttribut()
,我认为null
有不同的sql。如果是这种情况,则无法使用单个initialisationRequetePreparee
。您需要两个函数,或者需要一个initialisationRequetePreparee
内部逻辑,类似于以下内容:
PreparedStatement ps = ...
if (articleAttribute == null) {
// 3 ps.set functions
} else {
// 4 ps.set functions
}
return ps;