DataSet ds = new DataSet();
private static string sql = "select code as 核销代号, from_date as 开始日期, to_date as 结束日期, manual_no as 手册编号, re as 备注 from bms_cancel ";
private static string sqlC = Properties.Settings.Default.OracleConnectionString; //数据库链接字符串,确定没问题。
public static OracleDataAdapter oda = new OracleDataAdapter(sql, sqlC); private void FromCancel_Load(object sender, EventArgs e)
{
ds.Clear();
oda.Fill(ds,"table1");
dgv.DataSource = ds.Tables[0]; //dgv是一个datagridview 控件
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
oda.Update(ds, "table1");
MessageBox.Show("资料保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("资料保存失败,请检查资料的正确性!\n\r" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}我想实现的功能是在dgv中修改的数据能在点击保存按钮时保存到数据库的表中,可是实现不了,请高手指点,谢谢。
private static string sql = "select code as 核销代号, from_date as 开始日期, to_date as 结束日期, manual_no as 手册编号, re as 备注 from bms_cancel ";
private static string sqlC = Properties.Settings.Default.OracleConnectionString; //数据库链接字符串,确定没问题。
public static OracleDataAdapter oda = new OracleDataAdapter(sql, sqlC); private void FromCancel_Load(object sender, EventArgs e)
{
ds.Clear();
oda.Fill(ds,"table1");
dgv.DataSource = ds.Tables[0]; //dgv是一个datagridview 控件
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
oda.Update(ds, "table1");
MessageBox.Show("资料保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("资料保存失败,请检查资料的正确性!\n\r" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}我想实现的功能是在dgv中修改的数据能在点击保存按钮时保存到数据库的表中,可是实现不了,请高手指点,谢谢。
oda.Update(ds,"tableName");自己换一下!我这是ms sql!!
贴出完整的
这个你是update撒子东东????
其次,DataAdapter的Update没有CommandBuilder也没有自定义Update参照这个方法,传入的DataSet中都是要修改的数据。
public void Update(DataSet ds)
{
using (SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=xxx;User ID=sa;Password=sa"))
{
sqlconn.Open();
SqlTransaction tran = sqlconn.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
//所有行设为修改状态
dr.SetModified();
}
//为Adapter定位目标表
SqlCommand cmd = new SqlCommand(string.Format("select * from {0} where 1=0 ", ds.Tables[0].TableName), sqlconn, tran); SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(da);
da.AcceptChangesDuringUpdate = false;
SqlCommand updatecmd = new SqlCommand(string.Format(" UPDATE [{0}] SET [Name] = @Name WHERE ([ID] = @ID) ", ds.Tables[0].TableName));
//不修改源DataTable
updatecmd.UpdatedRowSource = UpdateRowSource.None;
da.UpdateCommand = updatecmd;
da.UpdateCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
da.UpdateCommand.Parameters.Add("@ID", SqlDbType.Int, 4, ds.Tables[0].Columns[0].ColumnName); da.UpdateBatchSize = 10000;
res = da.Update(ds.Tables[0]);
ds.AcceptChanges();
tran.Commit();
sqlconn.Close(); }
catch
{
tran.Rollback();
}
}
}