C#怎么在窗体程序中操作数据库数据
发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,本文小编为大家详细介绍"C#怎么在窗体程序中操作数据库数据",内容详细,步骤清晰,细节处理妥当,希望这篇"C#怎么在窗体程序中操作数据库数据"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来
千家信息网最后更新 2025年11月07日C#怎么在窗体程序中操作数据库数据
本文小编为大家详细介绍"C#怎么在窗体程序中操作数据库数据",内容详细,步骤清晰,细节处理妥当,希望这篇"C#怎么在窗体程序中操作数据库数据"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
一、界面布局
界面中有一个dataGridview、两个Button、两个Label和两个TextBox。
二、定义数据库操作的公共类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;using System.Windows.Forms;using System.Data;using MySql.Data.MySqlClient;namespace TemSys{ public class DBCtrl { private MySqlConnection m_ClientsqlConn; public DBCtrl() // 连接类型 { m_ClientsqlConn = new MySqlConnection(); try { m_ClientsqlConn.Dispose(); m_ClientsqlConn.Close(); m_ClientsqlConn.ConnectionString = "Database=dbName;Data Source=localhost;User Id=root;Password=123;charset=utf8"; m_ClientsqlConn.Open(); } catch (Exception ee) { MessageBox.Show(ee.Message); } } public DBCtrl(string IP, string DBname, string Uname, string Pword) // 创建连接 { m_ClientsqlConn = new MySqlConnection(); try { m_ClientsqlConn.Dispose(); m_ClientsqlConn.Close(); m_ClientsqlConn.ConnectionString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};charset=utf8", DBname, IP, Uname, Pword); m_ClientsqlConn.Open(); } catch (Exception ee) { MessageBox.Show(ee.Message); } } public void DBConn(string connStr) // 重载 创建连接 { try { m_ClientsqlConn.Close(); m_ClientsqlConn.ConnectionString = connStr; m_ClientsqlConn.Open(); } catch (Exception ee) { MessageBox.Show(ee.Message); } } public DataTable GetDataTable(string SQLstr) // 获取DataTable 一个表 { Console.Write("zcn==获取数据库连接,打开数据库"); try { if (m_ClientsqlConn.State == ConnectionState.Open) m_ClientsqlConn.Close(); m_ClientsqlConn.Open(); MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn); DataTable resultDS = new DataTable(); da.Fill(resultDS); return resultDS; } catch (Exception ee) { Console.Write("zcn==获取数据库连接,打开数据库异常异常"); //MessageBox.Show( ee.Message); m_logclass.WriteLogFilein(ee.Message, "GetDataTable.txt"); return null; } finally { m_ClientsqlConn.Close(); } } public DataTable GetDataTableUsing(string SQLstr) // 获取DataTable 一个表 { using (MySqlConnection m_ClientsqlConn = new MySqlConnection()) { } try { if (m_ClientsqlConn.State == ConnectionState.Open) m_ClientsqlConn.Close(); m_ClientsqlConn.Open(); MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn); DataTable resultDS = new DataTable(); da.Fill(resultDS); return resultDS; } catch (Exception ee) { //MessageBox.Show( ee.Message); return null; } } public List GetStringListfor(string lineName,DataTable dt) //根据某一列的名字 获取某个集合中该列的所有值 { List list = new List(); foreach (DataRow dr in dt.Rows) { list.Add((string)dr[lineName]); } return list; } public List GetDataRowfor(DataTable dt) //根据 datatable 获取每一行的数据的datarow { List list = new List(); foreach (DataRow dr in dt.Rows) { list.Add(dr); } return list; }/* public DataRow GetDataRowfor(string tablename,string ID) //根据ID号 返回对应行的 DataRow { string ss = "select * from " + tablename + " where ID = \'"+ID +"\'"; DataRow dr = new DataRow(); DataTable dt = GetDataTable(ss); dr = dt.Rows[0]; return dr; }*/ public DataTable GetDataTableOneLine(string SQLstr) // 获取DataTable 一个表中一行 { MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn); DataTable resultDS = new DataTable(); da.Fill(resultDS); return resultDS; } public DataTable GetDataSet_to_Table(string SQLstr) // 获取 dataset 多个表中 table { try { MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn); DataSet ds = new DataSet(); da.Fill(ds); return ds.Tables[0]; } catch { return null; } } public Boolean InsertDBase(string insString) { try { if (m_ClientsqlConn.State == ConnectionState.Open) m_ClientsqlConn.Close(); m_ClientsqlConn.Open(); MySqlCommand sqlcomd = new MySqlCommand(insString, m_ClientsqlConn); sqlcomd.ExecuteNonQuery(); return true; } catch (Exception ee) { return false; } finally { m_ClientsqlConn.Close(); } } public Boolean deleteRowfor(string tablename,int deleteID) //根据 ID 删除指定行 { try { string ss ="delete from "+ tablename +" where ID = "+ deleteID; if (m_ClientsqlConn.State == ConnectionState.Open) m_ClientsqlConn.Close(); m_ClientsqlConn.Open(); MySqlCommand sqlcmd = new MySqlCommand(ss, m_ClientsqlConn); sqlcmd.ExecuteNonQuery(); return true; } catch(Exception ee) { return false; } } public Boolean ModifyRowfor(string modifystr,string modifyID) // 根据 { try { string ss = modifystr + " where id = " + modifyID; if (m_ClientsqlConn.State == ConnectionState.Open) m_ClientsqlConn.Close(); m_ClientsqlConn.Open(); MySqlCommand sqlcmd = new MySqlCommand(ss, m_ClientsqlConn); sqlcmd.ExecuteNonQuery(); return true; } catch (Exception ee) { return false; } finally { m_ClientsqlConn.Close(); } } public void CloseDBase() // 参数类型 不同数据库连接 { m_ClientsqlConn.Close(); } }} 三、在界面中操作数据库方法
ps:数据库的配置信息保存在Config.ini文件中,如果仅是测试用的话,可以直接在
m_DataBase = new DBCtrl(ipstr, namestr, usernamestr, passwordstr);
处输入ip地址、数据库名、数据库用户名和密码即可
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace TemSys{ public partial class ModifyDevice : Form { [DllImport("kernel32")] //读写ini文件函数 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); DataTable dt = new DataTable(); private DBCtrl m_DataBase; public ModifyDevice() { InitializeComponent(); } //将所有的textBox值设为空 private void TextBoxNull() { textBox1.Text = ""; textBox2.Text = ""; } //设置Lab值 private void labelshow() { label1.Text = dataGridView1.Columns[0].HeaderText; label2.Text = dataGridView1.Columns[12].HeaderText; } //初始化界面 private void ModifyDevice_Load(object sender, EventArgs e) { StringBuilder retval = new StringBuilder(); GetPrivateProfileString("DBConfig", "dbip", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini"); string ipstr = retval.ToString(); GetPrivateProfileString("DBConfig", "dbname", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini"); string namestr = retval.ToString(); GetPrivateProfileString("DBConfig", "dbusername", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini"); string usernamestr = retval.ToString(); GetPrivateProfileString("DBConfig", "dbpassword", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini"); string passwordstr = retval.ToString(); m_DataBase = new DBCtrl(ipstr, namestr, usernamestr, passwordstr); initDataTable(); } private void initDataTable() { string ssp = string.Format("select * from device_info1"); dt = m_DataBase.GetDataTable(ssp); dataGridView1.DataSource = dt; labelshow(); } //双击dataGridView响应事件 private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { string index = dataGridView1.CurrentRow.Cells[0].Value.ToString(); if (label1.Text == "id") { string ssp = string.Format("select * from device_info1 where id='" + index + "'"); dt = m_DataBase.GetDataTable(ssp); //DataRow row = dt.Rows[0]; textBox1.Text = dt.Rows[0]["id"].ToString(); textBox2.Text = dt.Rows[0]["number"].ToString(); } } //点击修改按钮响应事件 private void btnModify_Click(object sender, EventArgs e) { bool flag = false; string ssp = string.Format("update device_info1 set number='" + textBox2.Text + "'"); flag = m_DataBase.ModifyRowfor(ssp, textBox1.Text); if (flag) { MessageBox.Show("修改成功!"); initDataTable(); } else { MessageBox.Show("修改失败!"); } } private void btnDelete_Click(object sender, EventArgs e) { bool flag = false; int currentIndex = (int)dataGridView1.CurrentRow.Cells[0].Value; Console.WriteLine("输出当前选中数据行:" + currentIndex); flag = m_DataBase.deleteRowfor("device_info1", currentIndex); if (flag) { MessageBox.Show("删除成功!"); initDataTable(); } else { MessageBox.Show("删除失败!"); } } }}读到这里,这篇"C#怎么在窗体程序中操作数据库数据"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
数据
数据库
界面
程序
窗体
C#
两个
文章
成功
一行
事件
内容
文件
类型
不同
妥当
信息
函数
参数
名字
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
软件开发费用如何支出
mfc ftp服务器
浦东新区网络技术开发咨询优势
无线网络安全认证类型
北京软件开发公司有多少
服务器移动app管理
域ftp服务器
石嘴山软件开发哪家服务好
水底数据库
泰兴直销网络技术市场
网络安全技术靠什么
主要收录会议论文的数据库是
软件开发黑帽子和白帽子
自己托管服务器还是阿里云
数据库中建立查询查姓氏
共筑网络安全主题黑板报
清华软件开发 教授
数据库设计和应用题
什么工作站服务器
星空壁纸引擎服务器是国内吗
企业双路服务器
国家网络安全宣传公益广告
游戏网络安全陷阱
服务器搭设
南天门网络技术有限公司招聘
数据库中属性名和属性值
2021年最新的数据库技术
网络安全教育简报文案
西安app软件开发报价单
帐套建立需要那些数据库