我试图一次在MS Access中插入多个记录,但它说
在SQL语句结束后找到的字符。
如何一次插入所有记录,这是我的代码。
DataTable中的示例记录;
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("STORE_NAM1");
dt.Columns.Add("STORE_ADD1");
dt.Columns.Add("STORE_ADD2");
dt.Columns.Add("PHONE");
dt.Columns.Add("FAX");
dt.Columns.Add("ABN_ACN_NO");
dt.Columns.Add("EMAIL");
dt.Columns.Add("WEB");
object[] o = { "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer" };
dt.Rows.Add(o);
object[] o2 = { "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer" };
dt.Rows.Add(o2);
object[] o3 = { "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer", "Qadeer" };
dt.Rows.Add(o3);
这是插入..
using (OleDbConnection con = new OleDbConnection(connectionAccess))
{
List<string> Rows = new List<string>();
string sCommand = "";
foreach (DataRow row in dt.Rows)
{
sCommand += "insert into store (STORE_NAM1, STORE_ADD1, STORE_ADD2, PHONE, FAX, ABN_ACN_NO, EMAIL, WEB) values ('"
+ row["STORE_NAM1"].ToString() + "', '"
+ row["STORE_ADD1"].ToString() + "', '"
+ row["STORE_ADD2"].ToString() + "', '"
+ row["PHONE"].ToString() + "', '"
+ row["FAX"].ToString() + "', '"
+ row["ABN_ACN_NO"].ToString() + "', '"
+ row["EMAIL"].ToString() + "', '"
+ row["WEB"].ToString() + "');";
//if I hard code values, this works fine with one insert
//sCommand = "insert into store(STORE_NAM1, STORE_ADD1, STORE_ADD2, PHONE, FAX, ABN_ACN_NO, EMAIL, WEB) values ('Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer');";
//this does not work with multiple records
//sCommand = "insert into store(STORE_NAM1, STORE_ADD1, STORE_ADD2, PHONE, FAX, ABN_ACN_NO, EMAIL, WEB) values ('Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer'); insert into store(STORE_NAM1, STORE_ADD1, STORE_ADD2, PHONE, FAX, ABN_ACN_NO, EMAIL, WEB) values ('Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer'); insert into store(STORE_NAM1, STORE_ADD1, STORE_ADD2, PHONE, FAX, ABN_ACN_NO, EMAIL, WEB) values ('Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer', 'Qadeer');";
try
{
using (OleDbCommand myCmd = new OleDbCommand(sCommand, con))
{
con.Open();
myCmd.CommandType = CommandType.Text;
int result = myCmd.ExecuteNonQuery();
Console.WriteLine(result +" records inserted");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
我也尝试过参数化方式。
答案 0 :(得分:1)
更改
sCommand += "insert...
要
sCommand = "insert...
你第一次通过循环插入字符串很好。在那之后,它变得越来越长。 Access只需要每个查询一个语句。