打开APP
userphoto
未登录

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

开通VIP
Winform 使用Ado.Net操作数据库

前言

    第二篇使用Ado.Net,其实这个方式是没什么可写的,因为大家如果有学习到数据库的话,这种方式理论上是必然要用到过的,当然,如果你直接跳过了最基础的方式而直接使用了ORM,那你要少好多学习的乐趣,哈哈哈,不过我相信,你总会遇到这样一个项目或者需求,让你回到这种最原始而又强大的方式。







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

开发工具:Visual Studio 2022

 









实现步骤

  1. 这种方式只要引入对应的数据库连接的DLL就行,所以只需要通过Nuget添加System.Data.SQLite即可
  2. 添加以下命名空间
using System.Data.SQLite;

  1. 定义数据库的连接字符串以及dataGridView的绑定数据源,由于Ado.Net对DataTable数据源非常友好,所以这里换成DataTable其实我觉得dataGridView对于DataTable的友好程度也要超过BindingList
readonly string dbConnStr = "Data Source=" + Application.StartupPath + "\\data.db"; DataTable bindTable = new DataTable();
  1. 查询
protected override void OnClick(EventArgs e) { base.OnClick(e); Checked = !Checked; }

  1. 新增
private void btn_add_Click(object sender, EventArgs e) { Form2 form = new Form2(); if (form.ShowDialog() == DialogResult.OK) { using (SQLiteConnection dbConn = new SQLiteConnection(dbConnStr)) { dbConn.Open(); SQLiteCommand cmd = new SQLiteCommand("insert into t_user(name,age) values(@name,@age)", dbConn); cmd.Parameters.Add(new SQLiteParameter("name", form.UserName)); cmd.Parameters.Add(new SQLiteParameter("age", new Random().Next(1, 100))); cmd.ExecuteNonQuery(); } 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 = dataGridView1[1,index].Value.ToString(); if (form.ShowDialog() == DialogResult.OK) { using (SQLiteConnection dbConn = new SQLiteConnection(dbConnStr)) { dbConn.Open(); SQLiteCommand cmd = new SQLiteCommand("update t_user set name=@name where id=@id", dbConn); cmd.Parameters.Add(new SQLiteParameter("name", form.UserName)); cmd.Parameters.Add(new SQLiteParameter("id", dataGridView1[0, index].Value)); cmd.ExecuteNonQuery(); } 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 (SQLiteConnection dbConn = new SQLiteConnection(dbConnStr)) { dbConn.Open(); SQLiteCommand cmd = new SQLiteCommand("delete from t_user where id=@id", dbConn); cmd.Parameters.Add(new SQLiteParameter("id", dataGridView1[0, index].Value)); cmd.ExecuteNonQuery(); } MessageBox.Show("删除成功"); btn_query_Click(null, null); }


实现效果

 


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



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#类型初始值设定项引发异常
SQLLite的使用
System.Data.SQLite
C#使用System.Data.SQLite操作SQLite
SQLite Helper for c#(1)
SQLite使用报告
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服