string str = "Data Source=VM121;Initial Catalog=TextData;User id=sa;Password=********";
SqlConnection conn = new SqlConnection(str);
conn.Open();
string sql = "select * from S_Table";
SqlDataAdapter sda = new SqlDataAdapter();
//SqlCommand cmd = new SqlCommand(sql,conn);
sda.SelectCommand = new SqlCommand(sql,conn);
SqlCommandBuilder sc = new SqlCommandBuilder(sda);
DataSet ds = new DataSet();
sda.Fill(ds, "s_table");
//修改某一数据<此操作不会改变数据库中的数据>
//DataRow row = ds.Tables["s_table"].Rows[2];//Row[?],?代表修改的是第几行的数据
//row.BeginEdit();
//row[1] = "tt";
//row[2] = "women";
//row[3] = "一班";
//row.EndEdit();
//#region
//添加一行数据
//DataRow row3 = ds.Tables["s_table"].NewRow();
//row3[0] = "12080301";
//row3[1] = "Alen";
//row3[2] = "女";
//row3[3] = "一班";
//row3[4] = "1561056317";
//ds.Tables["s_table"].Rows.Add(row3);
//#endregion
for (int i = 0; i < ds.Tables["s_table"].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables["s_table"].Columns.Count; j++)
{
Console.WriteLine(ds.Tables["s_table"].Rows[i][j]);
}
}
//删除某行数据
ds.Tables["s_table"].Rows[3].Delete();
//sda.DeleteCommand = sc.GetDeleteCommand();
try
{
sda.UpdateCommand = sc.GetUpdateCommand();
sda.DeleteCommand = sc.GetDeleteCommand();
sda.Update(ds, "s_table");
ds.Tables["s_table"].AcceptChanges();
//Console.WriteLine("11111");
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
sda.Dispose();
ds.Dispose();
conn.Close();
Console.ReadLine();
}
ds.Tables["s_table"].AcceptChanges();此语句一定放在Update之后,否则数据库更新不成功