简体   繁体   中英

How to convert c# Datetime into Foxpro Date

I've converted FOX PRO tables using OLEDB and I am using tables in c# ,when I am inserting data into tables it's working fine but when i am inserting date field(present day)date it's showing error data type mismatch.

dateformat dd/MM/yyyy only date no time.

string tdate = datetime.now.tostring("dd/MM/yyyy");

when I am inserting into tables I am passing value ctod('"+tdate+"');

string query = "select * from table1 where ordcust='" + account + "'"; 
OpenConnection(); 
OleDbCommand cmd = new OleDbCommand(query, con);
if (ds.Tables[0].Rows.Count > 0) 
{
   string ordcust = dr[0].ToString(); 
   string ordnum = dr[1].ToString(); 
   DateTime orddate = DateTime.Now; 
   string vara=orddate.ToString("dd/MM/yyyy"); 
   string cs = "insert into resulttable(ordercustomer,ordnumber,orddate) values ('" + ordcust + "','" + ordnum + "', ctod('" + vara + "') )";
}

I strongly suspect you are a victim of choosing the wrong data type . You should never store your DateTime values with their string representations. Just pass their values directly in a parameterized query .

My suggestions;

  • Define your DBTYPE_DATE on for OleDb Type which is mapped System.DateTime in .NET side which is mapped OleDbType.Date in parameter type.
  • Pass your DateTime.Now directly to your parameterized query.

Also be aware of: The case against DateTime.Now

What does it mean that you "converted" FoxPro tables using OLEDB? Your code doesn't look right, not only for FoxPro but for any SQL database. You should use parameters anyway. It would look like:

using (var con = new OleDbConnection(@"Provider=VFPOLEDB;Data Source=c:\Path To Your Data\"))
{
    string query = "select * from table1 where ordcust=?";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(query, con);
    cmd.Parameters.AddWithValue("p1", account);
    var reader = cmd.ExecuteReader();
    if (reader.Read())
    {
        string ordcust = (string)dr[0];
        string ordnum = (string)dr[1];
        DateTime orddate = DateTime.Now;
        string vara = orddate.ToString("dd/MM/yyyy");
        string cs = "insert into resulttable (ordercustomer,ordnumber,orddate) values (?, ?, ?)";

        var insertCommand = new OleDbCommand(cs, con);
        insertCommand.Parameters.AddWithValue("p1", ordcust);
        insertCommand.Parameters.AddWithValue("p2", ordnum);
        insertCommand.Parameters.AddWithValue("p3", orddate);

        insertCommand.ExecuteNonQuery();
    }
    con.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM