Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized query and NULL DateTime value

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();
}
like image 913
2 revs Avatar asked Jul 05 '26 00:07

2 revs


1 Answers

Something like the following should be what you want:

string sqlcmd = "INSERT INTO signatures (QASignature, QADate) VALUES (?, ?)";
using (System.Data.OleDb.OleDbCommand SQLCommand = new System.Data.OleDb.OleDbCommand(sqlcmd, Connection))
{
    SQLCommand.Parameters.Add(new OleDbParameter() { Name = "QASignature", Value = os.QASignature, DbType = DbType.String});
    SQLCommand.Parameters.Add(new OleDbParameter() { Name = "QADATE", Value = os.QADate, DbType = DbType.DateTime});
    SQLCommand.ExecuteNonQuery(); //Use ExecuteReader or ExecuteScalar when you want to return something
} 

If os.QADate is nullable (DateTime? or System.Nullable<DateTime>), then you would do the following:

if(os.QADate == null) //Could easily be os.QADate == DateTime.MinValue too, for example
{
    SQLCommand.Parameters.Add(new OleDbParameter() { Name = "@QADATE", Value = DBNull.Value, DbType = DbType.DateTime});
}
else{
    SQLCommand.Parameters.Add(new OleDbParameter() { Name = "@QADATE", Value = os.QADate, DbType = DbType.DateTime});
}

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.

like image 153
dash Avatar answered Jul 06 '26 13:07

dash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!