I'm getting a Syntax Error in the below code. From my testing, it's coming from the field "tax_month"
which is a DateTime
. I can't figure out how to insert a value in DateTime format.
Schema of that field:
ColumnName: tax_month,
ColumnOrdinal: 0,
ColumnSize: 6,
NumericPrecision: 10,
NumericScale: 0,
DataType: System.DateTime,
ProviderType: 23
This is my C# code:
string path = @"C:\Purchases\DATA\";
string fileName = "purchase.dbf";
DateTime tax_month = DateTime.FromOADate(41305);
private void button1_Click(object sender, EventArgs e)
{
OdbcConnection dbfConn = new OdbcConnection();
dbfConn.ConnectionString = @"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;Exclusive=No;Collate=Machine;NULL=NO;DELETED=YES;BACKGROUNDFETCH=NO;SourceDB=" + path;
dbfConn.Open();
OdbcCommand oCmd = dbfConn.CreateCommand(); // needed to query data
oCmd.CommandText = "INSERT INTO " + fileName + " ('tax_month') VALUES ("+tax_month+")";
int inserted = oCmd.ExecuteNonQuery();
dbfConn.Close();
MessageBox.Show("Number of Rows inserted:"+inserted);
}
Try to use a parameterized query and let the work to parse your datatime to the NET Framework code
using(OdbcConnection dbfConn = new OdbcConnection())
{
dbfConn.ConnectionString = @"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;Exclusive=No;Collate=Machine;NULL=NO;DELETED=YES;BACKGROUNDFETCH=NO;SourceDB=" + path;
dbfConn.Open();
OdbcCommand oCmd = dbfConn.CreateCommand(); // needed to query data
oCmd.CommandText = "INSERT INTO " + fileName + " +
"(tax_month,seq_no,tin,registered_name,last_name,first_name,middle_name,address1," +
"address2,gpurchase,gtpurchase,gepurchase,gzpurchase,gtservpurchase,gtcappurchase," +
"gtothpurchase,tinputtax,tax_rate) VALUES (" +
"?, 3, '222333445','TEST COMPANY','','','','DI MAKITA STREET','MANDALUYONG 1602', " +
"52107.14, 49107.14, 1000, 2000, 3000, 4000, 42107.14, 5892.86, 12)"
oCmd.Parameters.Add("@p1", OdbcType.DateTime).Value = tax_month;
int inserted = oCmd.ExecuteNonQuery();
}
Also, the column names should be written without single quotes around. The use of a parameter query has also the added benefit to avoid Sql Injection, though your code is not completely safe because the table name appended with the string concatenation