有人可以快速查看我的ado.net代码吗?我试图从数据集更新行,但它只是无法正常工作。我遗漏了一些基本的代码,它只是在逃避我。我已经验证DataRow实际上有正确的数据,因此行本身是准确的。
非常感谢提前。
try
{
//basic ado.net objects
SqlDataAdapter dbAdapter = null;
DataSet returnDS2 = new DataSet();
//a new sql connection
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Server=myserver.mydomain.com;"
+ "Database=mydatabase;"
+ "User ID=myuserid;"
+ "Password=mypassword;"
+ "Trusted_Connection=True;";
//the sqlQuery
string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21";
//another ado.net object for the command
SqlCommand cmd = new SqlCommand();
cmd.Connection = myConn;
cmd.CommandText = sqlQuery;
//open the connection, execute the SQL statement and then close the connection.
myConn.Open();
//instantiate and fill the sqldataadapter
dbAdapter = new SqlDataAdapter(cmd);
dbAdapter.Fill(returnDS2, @"AVLUpdateMessages");
//loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db
for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++)
{
DataRow row = returnDS2.Tables[0].Rows[i];
row.BeginEdit();
row["UpdatedText"] = @"This is a test...";
row.EndEdit();
}
//let's accept the changes
dbAdapter.Update(returnDS2, "AVLUpdateMessages");
returnDS2.AcceptChanges();
myConn.Close();
}
答案 0 :(得分:1)
我认为您需要在数据适配器中进行更新查询。我知道,这很糟糕......或者你可以使用CommandBuilder类自动生成CRUD操作的查询。
示例:http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset
答案 1 :(得分:0)
您可以使用SqlCommandBuilder来提供帮助。在Fill
调用之后,添加以下语句。这会将命令构建器与数据适配器相关联(如果有可用的主键),它应该为您生成更新语句。请注意,命令构建器后面有一些费用。它可能与其他所有内容相关性不大,但它确实涉及查看表的模式信息(获取主键信息,字段名称,字段类型等)并生成涉及所有字段的INSERT,DELETE和UPDATE语句。桌子。
SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
答案 2 :(得分:0)
等等,为什么不喜欢
update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21
如果您正在挑选一个表的所有行来一次更新一个,那么您可能做错了。 SQL是你的朋友。