在QODBC查询C#中插入日期和时间时出错

时间:2018-04-18 16:39:28

标签: c# datetime insert odbc qodbc

我收到错误

  

错误[42500]错误:3020 - 转换日期值“0000-00-48时出错。在字段中”salesOrder交易日期

我尝试插入的日期值为4/4/2018

我的代码

DateTime JobDate = Wintac_JobDate;

string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
                       " SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
                       "SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
                       ", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
                       "VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 +  "," +
                                    " '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
                                    "?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
                                    ""+ FQSaveToCache + ")";


OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);

sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;

MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate

if (Quantity != 0)
{
   if (sqlcmd2.ExecuteNonQuery() == 1)
   {
       if(FQSaveToCache == 0)
          MessageBox.Show(" added successfully.");
   }
}
  sqlcmd2.Dispose()

我尝试过转换变量作业日期

  • 日期时间
  • 短日期字符串
  • 长日期字符串
  • 将变量直接输入查询

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为主要问题是在那条线上;

sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()

您尝试在DateTime类型列上插入字符串表示。这相当错了。您需要直接传递DateTime值,而不是传递字符串表示。要了解这一习惯,请阅读Bad habits to kick : choosing the wrong data type

除此之外,我在你的代码中也看到了一些问题:

  1. 您应该始终使用parameterized queries。这种字符串连接可用于SQL Injection攻击。
  2. 使用using statement自动处理您的连接和命令,而不是手动调用callind Dispose方法,而您甚至在您的代码中认为这样做。