I’m working a program that is pulling a string field from an access database, separating out a name (first and last) from a date then save the name separately from the date in a different access database.
I’ve got everything done except some of the date values are null so I need to parametrize the SQL but I haven’t been able to figure out how to do make the parametrization work.
I’ve put in dummy values for the variable and it adds them to the table just fine. I’ve cut out the other variables in the code snippet below since they’re all repeats of what’s there. os is a list holding data from a structure.
string sqlcmd = "INSERT INTO signatures VALUES ('" + os.QASignature + "', 'QADate = @QADATE'";
System.Data.OleDb.OleDbCommand SQLCommand = new System.Data.OleDb.OleDbCommand(sqlcmd, Connection);
using (SQLCommand)
{
SQLCommand.Parameters.Add("@QADATE", System.Data.OleDb.OleDbType.Date).Value = os.QADate;
SQLDataReader = SQLCommand.ExecuteReader();
}
Something like the following should be what you want:
If os.QADate is nullable (
DateTime?orSystem.Nullable<DateTime>), then you would do the following:Note that you shouldn’t mix string concatenation and parameters like in your original example – it’s one or the other! And really, it should be just parameterization to guard against SQL Injection, and to gain other benefits (like easier typing and, in some RDBMS, parameterized queries perform better).
Also note that OleDBCommand does not benefit from named parameters – parameters must be added to the query in the order they appear in the SQL. This is why the SQL Query contains two question marks – they are simply placeholders.