C#如何在窗体程序中操作数据库数据

 更新时间:2022年4月19日 23:43  点击:358 作者:596785154

一、界面布局

界面中有一个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<string> GetStringListfor(string lineName,DataTable dt)    //根据某一列的名字  获取某个集合中该列的所有值
        {
            List<string> list = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add((string)dr[lineName]);
            }
            return list;
        }
        public List<DataRow> GetDataRowfor(DataTable dt)   //根据 datatable  获取每一行的数据的datarow
        {
            List<DataRow> list = new List<DataRow>();
            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("删除失败!");
            }
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/zcn596785154/article/details/81283722

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • PHP 数据库缓存Memcache操作类

    操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • php简单数据操作的实例

    最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25