前言
最近有些粉丝私信我有没有数据库操作相关的代码,联想之前在群里也有部分人问过一些数据库基础问题,翻了下文档、好像确实没写过相关的文章,所以接下来会通过使用三种方式来分别实现数据库的基本增删改查。
第一个就从Dapper起手吧,后面分别是Ado.Net和SqlSugar。
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
using Dapper;
using System.Data.SQLite;
dataGridView
的绑定数据源readonly string dbConnStr = "Data Source=" + Application.StartupPath + "\\data.db";
BindingList<T_User> bindList = new BindingList<T_User>();
private void btn_query_Click(object sender, EventArgs e)
{
using (IDbConnection dbConn = new SQLiteConnection(dbConnStr))
{
dbConn.Open();
var list = dbConn.Query<T_User>("select * from t_user").ToList();
bindList.SetData(list);
}
}
private void btn_add_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
if (form.ShowDialog() == DialogResult.OK)
{
using (IDbConnection dbConn = new SQLiteConnection(dbConnStr))
{
dbConn.Open();
dbConn.Execute("insert into t_user(name,age) values(@name,@age)", new { name = form.UserName, age = new Random().Next(1, 100) });
}
MessageBox.Show("添加成功");
btn_query_Click(null, null);
}
}
private void btn_edit_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
{
MessageBox.Show("未选中任何行");
return;
}
int index = dataGridView1.CurrentRow.Index;
Form2 form = new Form2();
form.UserName = bindList[index].Name;
if (form.ShowDialog() == DialogResult.OK)
{
using (IDbConnection dbConn = new SQLiteConnection(dbConnStr))
{
dbConn.Open();
dbConn.Execute("update t_user set name=@name where id=@id", new { name = form.UserName, id = bindList[index].Id });
}
MessageBox.Show("修改成功");
btn_query_Click(null, null);
}
}
private void btn_remove_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
{
MessageBox.Show("未选中任何行");
return;
}
int index = dataGridView1.CurrentRow.Index;
using (IDbConnection dbConn = new SQLiteConnection(dbConnStr))
{
dbConn.Open();
dbConn.Execute("delete from t_user where id=@id", new { id = bindList[index].Id });
}
MessageBox.Show("删除成功");
btn_query_Click(null, null);
}
实现效果
联系客服