此WinForms项目具有以下代码:
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EbosPr.Properties.Settings.Database1ConnectionString1"].ConnectionString);
SqlCommand scmd = new SqlCommand("Select * From CustCalls ", conn);
SqlDataAdapter sda = new SqlDataAdapter(scmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
this.dataGridView1.BindingContext[dt].EndCurrentEdit();
SqlCommandBuilder myBuilder = new SqlCommandBuilder(sda);
myBuilder.GetUpdateCommand();
sda.UpdateCommand = myBuilder.GetUpdateCommand();
sda.Update(dt);
它不会更新数据库,也没有错误。如何改进?
答案 0 :(得分:0)
我在一个小型内部实用程序中生成以下代码,它就像一个魅力:
public int UpdateSQLDataTable(string connectionString, string TableName, DataTable dtSource)
{
using (SqlConnection sConn = new SqlConnection(connectionString))
{
sConn.Open();
var transaction = sConn.BeginTransaction();
try
{
SqlCommand command = sConn.CreateCommand();
command.Transaction = transaction;
command.CommandText = string.Format("SELECT TOP 1 * FROM dbo.[{0}] WITH (NOLOCK)", TableName);
command.CommandType = CommandType.Text;
// timeout in seconds...
command.CommandTimeout = 30;
SqlDataAdapter sAdp = new SqlDataAdapter(command);
SqlCommandBuilder sCMDB = new SqlCommandBuilder(sAdp);
int affectedRecords = sAdp.Update(dtSource);
transaction.Commit();
return affectedRecords;
}
catch (Exception /* exp */)
{
transaction.Rollback();
throw;
}
}
}
答案 1 :(得分:0)
使用dataTable而不是DataSet ..这对我有用