打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Winform 使用Dapper操作数据库

前言

    最近有些粉丝私信我有没有数据库操作相关的代码,联想之前在群里也有部分人问过一些数据库基础问题,翻了下文档、好像确实没写过相关的文章,所以接下来会通过使用三种方式来分别实现数据库的基本增删改查。

第一个就从Dapper起手吧,后面分别是Ado.Net和SqlSugar。







开发环境:.NET Framework版本:4.8

开发工具:Visual Studio 2022

 









实现步骤

  1. 为了方便可以直接运行源代码。所以示例采用了SqLite数据库。所以第一步就是通过Nuget下载System.Data.SQLite
  2. 通过Nuget下载Dapper(其他任意渠道均可,由于是开源的,所以直接使用源代码也行)
  3. 分别引入以下命名空间
using Dapper;using System.Data.SQLite;

  1. 定义数据库的连接字符串以及dataGridView的绑定数据源
readonly string dbConnStr = "Data Source=" + Application.StartupPath + "\\data.db"; BindingList<T_User> bindList = new BindingList<T_User>();
  1. 查询
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); } }

  1. 新增
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); } }

  1. 编辑
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); } }

  1. 删除
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); }

实现效果

 


☛☛☛点击此处下载源码☚☚☚



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
C#导出EXCEL格式
TreeView控件与SQL数据库的应用(遍历算法)
C# excel文件导入导出
dataGridView移除多行
Extjs----Ext.Message以及Window弹出窗口
Dapper 衣冠楚楚
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服