Binding NULL in JAVA for MySQL PreparedStatment?

醉酒当歌 提交于 2019-12-24 09:25:33

问题


MySQL uses "IS NULL" instead of "NULL" so how do i bind variable to achieve the same ?

Right now i tried with this

selectStmt.setNull( 2, java.sql.Types.VARCHAR );

when i printed "java.sql.Types.VARCHAR" shows value = 12 ? If so how does this set " IS NULL" in preparedstatment ?

MORE DETAILS:

i.e I am interested in querying (MySQL) for null if i have string = " " in input. So logic goes like this,

Connection c = SQLCon.connect();
PreparedStatement selectStmt = c.prepareStatement( "select * from "
                                    + TableName
                                    + " where P = ? AND M = ? AND PR = ? AND DR = ? " );


if ( P.trim().equals( "" ) ) 
{
   selectStmt.setNull( 1, java.sql.Types.VARCHAR );
} else 
{
   selectStmt.setString( 1, P );
}

if ( M.trim().equals( "" ) ) 
{
   selectStmt.setNull( 2, java.sql.Types.VARCHAR );
} else 
{
   selectStmt.setString( 2, M );
}

Please advice


回答1:


If you want to match a column in a where clause that might be null with a parameter that might be null, you actually need to bind it twice, because in SQL a null doesn't equal anything else, even another null.

PreparedStatement stmt = conn.prepareStatement("select * from foo where (? is null and bar is null) or (bar = ?)");
col = 1;
setVarchar(stmt, col++, var);
setVarchar(stmt, col++, var);

void setVarchar(PreparedStatement stmt, int col, String var)
{
  if (var == null)
    stmt.setNull(col, java.sql.Types.VARCHAR);
  else
    stmt.setString(col, var);
}



回答2:


It seems odd, but you do:

if (variable == null) {
  selectStmt.setNull(2, java.sql.Types.VARCHAR);
} else {
  ...
}

the reason behind this is because NULL is a value in a database, and not having a value is null in Java. Occasionally, you need to differentiate between getting back a NULL from the database as opposed to getting back nothing from the database.




回答3:


it's an xml input and on UI user see blank for NULL and hence to send blank as input

if ( P.trim().equals( "" ) )
  {
    sql += "P IS NULL";
  }
   else
  {
    sql += "P = ?";
  }

PreparedStatement selectStmt = c.prepareStatement( sql );

int i = 1;
// used to prevent index out of range issues

// Binding values for non-null strings ONLY
 if ( !(P.trim().equals( "" )) )
  {
    selectStmt.setString( i, P );
  i++;
  }


来源:https://stackoverflow.com/questions/11961486/binding-null-in-java-for-mysql-preparedstatment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!