我写了个程序,用的OleDbCommandBuilder来更新数据,代码如下:
private void FormMain_Load(object sender, EventArgs e)
{
string file_name = Application.StarupPath + @"\test.mdb"; //本地数据库在bin里面
string password = "123";
string ConnectionString = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source='{0}';Persist Sercurity Info=false; JET OLEDB:Database Password={1}", file_name, password);
conn = new OleDbConnection(ConnectionString);
string sql = "SELECT * FROM test";//test为表名
da = new OleDbDataAdapter(sql, conn);
ds = new DataSet();
da.Fill(ds);
cb = new OleDbCommandBuilder(da);
}
private void btnImport_Click(object sender,EventArgs e) //更新数据库
{
DataTable dt = this.dataset1.Tables[0]; //dataset1是我新设立的一个DataSet,取的是excel里面的数据
for (int i = 0; i < dt.Rows.Count; i++)
{
ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);
Application.DoEvents();
}
da.Update(ds);//在此处更新数据
MessageBox.Show("提示操作成功。");
}
//用上面的代码,在数据库里面没数据的时候,更新很快,运行成功
但是数据库里面有数据的时候,我添加了一条语句
ds.Clear();在for循环的前面
for (int i = 0; i < dt.Rows.Count; i++)
{
ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);
Application.DoEvents();
}
da.Update(ds);//在此处更新数据
MessageBox.Show("提示操作成功。");
然后运行,就会报错,说数据库重复主键不能更新成功,
请问下各位高手,这是怎么回事,
private void FormMain_Load(object sender, EventArgs e)
{
string file_name = Application.StarupPath + @"\test.mdb"; //本地数据库在bin里面
string password = "123";
string ConnectionString = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source='{0}';Persist Sercurity Info=false; JET OLEDB:Database Password={1}", file_name, password);
conn = new OleDbConnection(ConnectionString);
string sql = "SELECT * FROM test";//test为表名
da = new OleDbDataAdapter(sql, conn);
ds = new DataSet();
da.Fill(ds);
cb = new OleDbCommandBuilder(da);
}
private void btnImport_Click(object sender,EventArgs e) //更新数据库
{
DataTable dt = this.dataset1.Tables[0]; //dataset1是我新设立的一个DataSet,取的是excel里面的数据
for (int i = 0; i < dt.Rows.Count; i++)
{
ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);
Application.DoEvents();
}
da.Update(ds);//在此处更新数据
MessageBox.Show("提示操作成功。");
}
//用上面的代码,在数据库里面没数据的时候,更新很快,运行成功
但是数据库里面有数据的时候,我添加了一条语句
ds.Clear();在for循环的前面
for (int i = 0; i < dt.Rows.Count; i++)
{
ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);
Application.DoEvents();
}
da.Update(ds);//在此处更新数据
MessageBox.Show("提示操作成功。");
然后运行,就会报错,说数据库重复主键不能更新成功,
请问下各位高手,这是怎么回事,
你只是晴空了DataSet
没有清空原文件的数据
比如我数据库里面的数据为:
索引 一月 2月 3月 4月
1 12 0 0 0
2 36 0 0 0
然后到2月,我想把数据库变成这样:
索引 一月 2月 3月 4月
1 12 21 0 0
2 36 34 0 0
我想用OleDbCommandBuilder更新数据,应该怎么做,最好是能给点简单代码,谢谢了