sjain
sjain

Reputation: 23344

Update table field value to null programmatically

It is well known that how to set the field value to null by a simple query like -

UPDATE your_table
SET    your_column = NULL
WHERE  id = 1;

But pro-grammatically, which one is correct way to update the field value to null -

db.execSQL("UPDATE  your_table SET your_column='" + null + "WHERE id='" + myid + "'");

OR

db.execSQL("UPDATE  your_table SET your_column= NULL WHERE id='" + myid + "'");

Thanks

Upvotes: 0

Views: 4180

Answers (2)

PermGenError
PermGenError

Reputation: 46418

I would go with PreparedStatement.

String query="UPDATE  your_table SET your_column= ? WHERE id=?");
PreparedStatement stmnt = conn.prepareStatement(query);
if(colyouAretryingtopass == null){]
  stmnt.setNull(1, Types.VARCHAR);
}

Upvotes: 3

James
James

Reputation: 1571

The correct way is to use bind variables, depending on the framework you are using this is done in different ways.

You query should be something like follows;

String query = "UPDATE your_table SET your_column = null WHERE id = ?";
executeQuery(query, id);

Where executeQuery(String query, Object... args) is the the DB access method of your choice.

If you don't use bind variables you are;

a) Vunerable to SQL injection.
b) Losing performance by not utilising query cache on the database.

Upvotes: 2

Related Questions