I have tried few codes from my end to insert a DataTable inside a Access db.
Below is the code:
public void WriteToAccess(DataTable dt)
{
string strDSN = "DSN=MYDSN";
string cmdText="Insert into AccessTable (ColumnA,ColumnB,ColumnC,ColumnD,ColumnE,ColumnF,ColumnG,ColumnH) Values (@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8)";
using (OdbcConnection cn = new OdbcConnection(strDSN))
{
using (OdbcCommand cmd = new OdbcCommand(cmdText, cn))
{
cn.Open();
foreach (DataRow r in dt.Rows)
{
cmd.Parameters.AddWithValue("@p1", r["ColumnA"].ToString());
cmd.Parameters.AddWithValue("@p2", r["ColumnB"].ToString());
cmd.Parameters.AddWithValue("@p3", r["ColumnC"].ToString());
cmd.Parameters.AddWithValue("@p4", r["ColumnD"].ToString());
cmd.Parameters.AddWithValue("@p5", r["ColumnE"].ToString());
cmd.Parameters.AddWithValue("@p6", r["ColumnF"].ToString());
cmd.Parameters.AddWithValue("@p7", r["ColumnG"].ToString());
cmd.Parameters.AddWithValue("@p8", r["ColumnH"].ToString());
cmd.ExecuteNonQuery();//Exception at this line
}
}
}
The DataTable to be inserted has 8 columns, the table in Access which i have created also has 8 columns.
When I execute the above piece of code, I encounter an exception. It says that:
ERROR [07002ױ] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 8.
I'm providing 8 params, yet it throws the error.
Can anybody let me know what I am doing wrong?