C#ADO.NET基础二
2021-06-08 11:02
标签:否则 datatable nec http display count one builder tar DataAdapter的使用,批量增删改 注意:DataTable的删除只能用 dataTable.Rows[i].Delete()不能用DataRow.RemoveAt和DataRow.Remove,否则更新数据库不成功 参考:https://www.cnblogs.com/zouhao/p/9977767.html 针对DataSet或者DataTable进行的增,删,改操作,可以合在一起批量执行。 C#ADO.NET基础二 标签:否则 datatable nec http display count one builder tar 原文地址:https://www.cnblogs.com/yaosj/p/10697789.html1.使用DataAdapter查询
private void Select2()
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(connStrl))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select name,age from test";
DataTable dataTable = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dataTable);
if (dataTable != null)
{
for (int i = 0; i )
{
DataRow row = dataTable.Rows[i];
string name = row["name"].ToString();
int age = int.Parse(row["age"].ToString());
textBox1.Text += $"name:{name} age:{age}\r\n";
}
}
}
}
}
catch (Exception)
{
throw;
}
}
2.批量增
private void btnBatchAdd_Click(object sender, EventArgs e)
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(connStrl))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select id,name,age from test";
DataTable dataTable = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dataTable);
for (int i = 0; i 10; i++)
dataTable.Rows.Add(null, "张8", 20);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(dataTable.GetChanges());
dataTable.AcceptChanges();
}
}
}
catch (Exception ex)
{
throw;
}
}
3.批量改
private void btnBatchUpdate_Click(object sender, EventArgs e)
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(connStrl))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select id,name,age from test";
DataTable dataTable = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
if (row["name"].ToString() == "张8")
row["name"] = "张一";
}
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(dataTable.GetChanges());
dataTable.AcceptChanges();
}
}
}
catch (Exception ex)
{
throw;
}
}
4.批量删
private void btnBatchDelete_Click(object sender, EventArgs e)
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(connStrl))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select id,name,age from test";
DataTable dataTable = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dataTable);
for (int i = 0; i )
dataTable.Rows[i].Delete();
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(dataTable.GetChanges());
dataTable.AcceptChanges();
}
}
}
catch (Exception ex)
{
throw;
}
}
5.总结
上一篇:Winform 窗口拖动
下一篇:C#winform自定义滚动条