我尝试将数据从C#的数据网格控件批量插入到MS-Access数据库文件中。我编写了如下代码:
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\\SoftwareModule\\insurance.mdb;");
try
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = myConnection;
myConnection.Open();
int rowsCount = dbChequeGrid.Rows.Count;
int rowsInserted = 0;
for (int i = 0; i < rowsCount; i++)
{
string StrQuery = "INSERT INTO cust (clientname,clientaddress,clientfathername)VALUES (@id,@CourseName,@Credits)";
comm.CommandText = StrQuery;
comm.Parameters.AddWithValue("@id", dbChequeGrid.Rows[i].Cells[0].Value);
comm.Parameters.AddWithValue("@CourseName", dbChequeGrid.Rows[i].Cells[1].Value);
comm.Parameters.AddWithValue("@Credits", dbChequeGrid.Rows[i].Cells[2].Value);
if (comm.ExecuteNonQuery() > 0)
{
rowsInserted++;
}
comm.Parameters.Clear();
}//end of for loop
if (rowsCount == rowsInserted)
{
MessageBox.Show("All Rows Inserted Successfully!");
}
else
{
MessageBox.Show("All Rows Not Inserted Successfully!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
但每次运行此代码时,都会出现以下错误。
参数&#34; @ someparameter&#34;没有默认值。
我浏览了很多网站,但没有发现我的代码有什么问题。
答案 0 :(得分:0)
不幸的是,我没有足够的声誉发表评论但尝试这些事情:
答案 1 :(得分:0)
我最好的猜测是dbChequeGrid.Rows [i] .Cells [0] .Value为空,并且因为没有默认值它会爆炸。
类似
comm.Parameters.AddWithValue("@id", (dbChequeGrid.Rows[i].Cells[0].Value==null?"somedfaultvalue":dbChequeGrid.Rows[i].Cells[0].Value));
应该为你做的伎俩。您还可以在执行插入之前执行一些错误检查。像
这样的东西 for (int i = 0; i < rowsCount; i++)
{
if(dbChequeGrid.Rows[i].Cells[0].Value != null){
string StrQuery = "INSERT INTO cust (clientname,clientaddress,clientfathername)VALUES (@id,@CourseName,@Credits)";
comm.CommandText = StrQuery;
comm.Parameters.AddWithValue("@id", dbChequeGrid.Rows[i].Cells[0].Value);
comm.Parameters.AddWithValue("@CourseName", dbChequeGrid.Rows[i].Cells[1].Value);
comm.Parameters.AddWithValue("@Credits", dbChequeGrid.Rows[i].Cells[2].Value);
if (comm.ExecuteNonQuery() > 0)
{
rowsInserted++;
}
comm.Parameters.Clear();
}else{
//do some sort of error handling
}
}//end of for loop
任何一种方法都可以防止NULL出现在你的@id参数中。在尝试将它们插入数据库之前,我会检查所有参数以确定它们是否正确。