c# 清空access数据库中的表格的内容

发布于:2021-07-20 04:53:36

1、问题描述


我想先从access数据库中读取其中一张表的内容,并将表的内容显示在listview中,然后,对listview中的数据进行操作,如增删改,然后将修改完的数据再保存到数据库中。这里就需要先将数据库中的数据清零,然后再保存。怎么将数据库清零呢?


2、解决方法


private void button4_Click(object sender, EventArgs e)
{
//连接数据库
connection = new OleDbConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ToString();
connection.Open();
cmd = new OleDbCommand();
cmd.Connection = connection;

//清空数据表
cmd.CommandText = "DELETE FROM data";
cmd.ExecuteNonQuery();

foreach (ListViewItem lvi in listView1.Items) // 遍历整个listview将listview中的数据导出到数据库
{
//cmd.Parameters.Clear();
string strUserID = "", strCheckMode = "", strInoutMode = "", strDate = "";
strUserID = lvi.SubItems[1].Text;
strCheckMode = lvi.SubItems[2].Text;
strInoutMode = lvi.SubItems[3].Text;
strDate = lvi.SubItems[4].Text;
string cmdString = "insert into data([姓名],[性别],[电话],[部门]) values( + strUserID + , + strCheckMode + , + strInoutMode + , + strDate + )";
cmd.CommandText = cmdString;
cmd.ExecuteNonQuery();
//cmd.Dispose();
}
connection.Close();
//刷新数据表
load_data();
}

public void load_data()
{
connection = new OleDbConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ToString();
connection.Open();
try
{
string sql = "select * from [data]";
OleDbDataReader oleDbDataReader = new OleDbCommand(sql, connection).ExecuteReader();
listView1.Items.Clear();
listView1.BeginUpdate();//数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
for (int i = 1; oleDbDataReader.Read(); i++)//遍历查询结果
{
ListViewItem listViewItem = new ListViewItem();
listViewItem.Text = i + "";//listview的每一行的第一项
listViewItem.SubItems.Add(oleDbDataReader.GetString(1));//其余子项
listViewItem.SubItems.Add(oleDbDataReader.GetString(2));
listViewItem.SubItems.Add(oleDbDataReader.GetString(3));
listViewItem.SubItems.Add(oleDbDataReader.GetString(4));
listView1.Items.Add(listViewItem);//将这行添加到listview中
}
listView1.EndUpdate();//结束数据处理,UI界面一次性绘制。
}
catch
{
MessageBox.Show(this.Text, "数据库出错!");
}
connection.Close();

}

参考文档:


【1】https://blog.csdn.net/u011981242/article/details/50816060?utm_source=blogxgwz7&utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-10&spm=1001.2101.3001.4242


【2】https://www.yuanmacha.com/11303689139.html


?

相关推荐

最新更新

猜你喜欢