本文主要是介绍SqlDataAdapter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数据库读取数据,修改后并更新到数据库
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword";
conn.Open();
SqlDataAdapter dap = new SqlDataAdapter("select * from table where id = 1", conn);
//如果不加这句,dap.Update(ds);将会报错:当传递具有已修改行的 DataRow 集合时,更新要求有效的 UpdateCommand。
SqlCommandBuilder build = new SqlCommandBuilder(dap);
var ds = new DataSet();
dap.Fill(ds); // 如果指定了表名dap.Fill(ds,"tableName"); 则dap.Update(ds.tables[0]);
//修改ds中的数据
ds.Tables[0].Rows[0][1] = "xxx";
dap.Update(ds);
conn.Dispose();
conn.Close();
}
说明:
dap.Update(ds); 调用前,要先设置更新需要的相关命令;可以使用 SqlCommandBuilder 对象,
利用SqlCommandBuilder 对象能够自动生成 insert、update、delete 命令
这篇关于SqlDataAdapter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!