dataset更新数据库

来源:百度知道 编辑:UC知道 时间:2024/05/30 08:49:20
Strin SQL = "Select Top 20 * From SysKf Order By ID Desc";
SqlConnection conn = new SqlConnection(game.usersqlstr());
SqlCommand cmd = new SqlCommand(SQL, conn);
SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();
sqlDataAdapter1.SelectCommand = cmd;
conn.Open();

DataSet ds = new DataSet();

sqlDataAdapter1.Fill(ds, "gamescore");
SqlCommandBuilder objBuilder = new SqlCommandBuilder(sqlDataAdapter1);
sqlDataAdapter1.UpdateCommand = objBuilder.GetUpdateCommand();
sqlDataAdapter1.Update(ds, "gamescore");
ds.AcceptChanges();
conn.Close(); conn.Dispose();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "gamescore";

为何不能更新数据库,最好在我这些代码的基础上给我修改一下,谢谢,是WINFORM
1楼的朋友:
sqlDataAd

你的代码更新不了数据
因为在你要提交更新前数据集是即时查询数据库的
没有获取当前修改的数据

思路是这样的:
先查询,绑定数据集(要更新的数据集需要设置为当前模块的变量)
等你在datagridview修改数据后继续进行下面的操作
然后是再在其他的事件中提交修改

比如:
你在某个窗体内定义
SqlConnection conn;
DataSet ds = new DataSet();
SqlCommand cmd ;
SqlDataAdapter sqlDataAdapter1;

在fromload中添加如下代码(没有测试,复制了你的代码)
String SQL = "Select Top 20 * From SysKf Order By ID Desc";
SqlConnection conn = new SqlConnection(game.usersqlstr());
SqlCommand cmd = new SqlCommand(SQL, conn);
SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();
sqlDataAdapter1.SelectCommand = cmd;
conn.Open();
sqlDataAdapter1.Fill(ds, "gamescore");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "gamescore";
conn.Close();
conn.Dispose();

然后放一个按钮,在click事件中处理:
if(conn.State.Equals(ConnectionState.Closed))
conn.Open();

SqlCommand