Reputation: 89
I am trying to use parameters for a DB2 query using ODbc in C#, but the Timestamp field is giving me issues. I am using DB2 Client 9.7 and updateDate is a DateTime type. Here is my code:
string commandString = "INSERT INTO DATABASENAME(USERNAME, UPDATE_DATE) VALUES ('?', TIMESTAMP_FORMAT('?', 'YYYY-MM-DD HH24:MI:SS'))";
OdbcConnection con = new OdbcConnection(conString);
OdbcCommand command = new OdbcCommand(commandString, con);
command.Parameters.AddWithValue("?username", userName);
command.Parameters.AddWithValue("?update_date", updateDate.ToString("yyyy-MM-dd HH:mm:ss"));
//execute the stuff
con.Open();
command.ExecuteNonQuery();
con.Close();
This is the error I am receiving:
ERROR [42815] [IBM][CLI Driver][DB2] SQL0171N The data type, length or value of the argument for the parameter in position "1" of routine "SYSIBM.TIMESTAMP_FORMAT" is incorrect. Parameter name: "". SQLSTATE=42815
I have also tried using the regular TIMESTAMP() function included in DB2 using both formats it accepts (Ex. TIMESTAMP ('2016-10-20-12.00.00.000000') TIMESTAMP ('2016-10-20 12:00:00')), but that gives me this error:
ERROR [22007] [IBM][CLI Driver][DB2] SQL0180N The syntax of the string representation of a datetime value is incorrect. SQLSTATE=22007
Anyone know where I am going wrong?
EDIT: It works without using parameters, can parameters not be used with DB2?
Upvotes: 0
Views: 2510
Reputation: 18945
I have no way of testing this but I think you should not enclose parameter markers in quotes, they are parameters, not literals. Your statement should look like
string commandString = "INSERT INTO DATABASENAME(USERNAME, UPDATE_DATE) VALUES (?,?)";
and then you also won't need double conversion from DateTime
to string to TIMESTAMP
:
command.Parameters.AddWithValue("?username", userName);
command.Parameters.AddWithValue("?update_date", updateDate);
Upvotes: 2
Reputation: 17472
string commandString = "INSERT INTO DATABASENAME(USERNAME, UPDATE_DATE) VALUES ('?','?')";
OdbcConnection con = new OdbcConnection(conString);
OdbcCommand command = new OdbcCommand(commandString, con);
OdbcParameter p1 = command.CreateParameter();
p1.DbType = DbType.AnsiString;
p1.Value = userName;
command.Parameters.Add(p1);
OdbcParameter p2 = command.CreateParameter();
p2.DbType = DbType.AnsiString;
p2.Value = updateDate.ToString("yyyy-MM-dd HH:mm:ss");
command.Parameters.Add(p2);
con.Open();
command.ExecuteNonQuery();
con.Close();
Upvotes: 0
Reputation: 17472
try it:
string commandString =string.format("INSERT INTO DATABASENAME(USERNAME, UPDATE_DATE) VALUES ('{0}', '{1}')", userName, updateDate.ToString("yyyy-MM-dd.HH.mm.ss.ffffff"));
OdbcConnection con = new OdbcConnection(conString);
OdbcCommand command = new OdbcCommand(commandString, con);
//execute the stuff
con.Open();
command.ExecuteNonQuery();
con.Close();
Upvotes: 0
Reputation: 17472
may be an error on timestamp format.
Try to do updateDate.ToString("yyyy-MM-dd.HH.mm.ss.ffffff"));
Upvotes: 0