文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

C#连接MySQL数据库

2023-10-28 06:50

关注

目录

一、引用MySql.Data.dll文件

二、连接、关闭数据库

三、数据库增删改查

附:完整代码


一、引用MySql.Data.dll文件

创建C#窗体应用程序,解决方案资源管理器中找到“引用”,右键,选择添加引用。

在MySQL的安装目录下找到MySql.Data.dll文件,选择添加 ,再点击确定。

注:如果程序可能多人互传,MySql.Data.dll文件建议复制到项目文件夹内,防止在其他电脑上找不到该文件路径。

二、连接、关闭数据库

引入命名空间

using MySql.Data.MySqlClient;

定义连接字段

设置端口号、用户密码、数据库名等

string sql_ip = "127.0.0.1";  //IPstring sql_port = "3306"; //端口号string sql_user = "root";  //用户名  string sql_pw = "power123";  //密码string sql_name = "my_data"; //数据库名string sql_con_state = "off";  //连接状态

连接、关闭数据库

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using MySql.Data.MySqlClient;//数据库namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        string sql_ip = "127.0.0.1";  //IP        string sql_port = "3306"; //端口号        string sql_user = "root";  //用户名          string sql_pw = "power123";  //密码        string sql_name = "my_data"; //数据库名        string sql_con_state = "off";  //连接状态        MySqlConnection sql_Test;        ///         /// 连接数据库        ///         ///         public int connect_sql()        {            string ConnectionString = "server = " + sql_ip + "; userid = " + sql_user + "; password = " + sql_pw + "; database =" + sql_name + "; persistsecurityinfo = True;SslMode=None ;Charset=utf8;";     // string ConnectionString = "server = " + this.sql_ip.Text + "; userid = "+this.sql_user.Text+"; password = "+ this.sql_pw.Text + "; database ="+ this.sql_name.Text + "; persistsecurityinfo = True;";            sql_Test = new MySqlConnection(ConnectionString);            try            {                sql_Test.Open();                Console.WriteLine("数据库连接成功");//打印信息                sql_con_state = "on";            }            catch (MySqlException ex)            {                Console.WriteLine(ex.Message);//打印错误信息                sql_con_state = "off";                return -1;            }            return 0;        }        ///         /// 关闭数据库        ///         ///         public void close_sql()        {            sql_con_state = "off";            sql_Test.Close();                   }    }}

三、数据库增删改查

增加

        ///         /// 增加        ///         /// 表名         /// 内容        /// 值        ///         public int insert_data(string table_name, string content, string value)        {            string sql;            sql = "insert into " + table_name + " (" + content + ") value (" + value + ")";            if (content == "" || value == "" || table_name == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }

删除

        ///         /// 删除        ///         /// 表名        /// 条件        ///         public int del_data(string table_name, string condition)        {            string sql;            sql = "delete from " + table_name + " where " + condition;            if (table_name == "" || condition == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }

修改

        ///         /// 修改        ///         /// 表名        /// 内容        /// 条件        ///         public int update_data( string table_name, string content, string condition)        {            string sql;            sql = "update " + table_name + " set " + content + " where " + condition;            if (content == "" || table_name == "" || condition == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }

查询

        ///         /// 查询        ///         /// 表名        /// 内容        /// 条件        ///         public DataTable db_select(string table_name, string content, string condition)        {            string sql;            DataTable dt = new DataTable();            if (sql_con_state == "on")            {                if (condition == "")                {                    sql = "select " + content + " from " + table_name; //查找全部                    if (content == "" || table_name == "" )                    {                        Console.WriteLine("语法错误 " + sql);//打印错误信息               }                }    else                {                    sql = "select " + content + " from " + table_name + " where " + condition;//按照条件查找                    if (content == "" || table_name == "" || condition == "")                    {                        Console.WriteLine("语法错误 " + sql);//打印错误信息               }                }    MySqlCommand cmd = new MySqlCommand(sql, sql_Test);                MySqlDataAdapter mda = new MySqlDataAdapter(cmd); //获取结果集                mda.Fill(dt);            }            else            {                Console.WriteLine("数据库未连接!");//打印信息            }            return dt;        }

附:完整代码

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using MySql.Data.MySqlClient;//数据库namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        string sql_ip = "127.0.0.1";  //IP        string sql_port = "3306"; //端口号        string sql_user = "root";  //用户名          string sql_pw = "power123";  //密码        string sql_name = "my_data"; //数据库名        string sql_con_state = "off";  //连接状态        MySqlConnection sql_Test;        ///         /// 连接数据库        ///         ///         public int connect_sql()        {            string ConnectionString = "server = " + sql_ip + "; userid = " + sql_user + "; password = " + sql_pw + "; database =" + sql_name + "; persistsecurityinfo = True;SslMode=None ;Charset=utf8;";     // string ConnectionString = "server = " + this.sql_ip.Text + "; userid = "+this.sql_user.Text+"; password = "+ this.sql_pw.Text + "; database ="+ this.sql_name.Text + "; persistsecurityinfo = True;";            sql_Test = new MySqlConnection(ConnectionString);            try            {                sql_Test.Open();                Console.WriteLine("数据库连接成功");//打印信息                sql_con_state = "on";            }            catch (MySqlException ex)            {                Console.WriteLine(ex.Message);//打印错误信息                sql_con_state = "off";                return -1;            }            return 0;        }        ///         /// 关闭数据库        ///         ///         public void close_sql()        {            sql_con_state = "off";            sql_Test.Close();                   }        ///         /// 增加        ///         /// 表名         /// 内容        /// 值        ///         public int insert_data(string table_name, string content, string value)        {            string sql;            sql = "insert into " + table_name + " (" + content + ") value (" + value + ")";            if (content == "" || value == "" || table_name == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }        ///         /// 删除        ///         /// 表名        /// 条件        ///         public int del_data(string table_name, string condition)        {            string sql;            sql = "delete from " + table_name + " where " + condition;            if (table_name == "" || condition == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }        ///         /// 修改        ///         /// 表名        /// 内容        /// 条件        ///         public int update_data( string table_name, string content, string condition)        {            string sql;            sql = "update " + table_name + " set " + content + " where " + condition;            if (content == "" || table_name == "" || condition == "")            {                Console.WriteLine("语法错误 "+ sql);//打印错误信息                return -1;            }            if (sql_con_state != "on")            {                Console.WriteLine("数据库未连接!");//打印信息                return -2;            }            int res;            MySqlCommand cmd = new MySqlCommand(sql, sql_Test);            res = cmd.ExecuteNonQuery();            return res;        }        ///         /// 查询        ///         /// 表名        /// 内容        /// 条件        ///         public DataTable db_select(string table_name, string content, string condition)        {            string sql;            DataTable dt = new DataTable();            if (sql_con_state == "on")            {                if (condition == "")                {                    sql = "select " + content + " from " + table_name; //查找全部                    if (content == "" || table_name == "" )                    {                        Console.WriteLine("语法错误 " + sql);//打印错误信息               }                }    else                {                    sql = "select " + content + " from " + table_name + " where " + condition;//按照条件查找                    if (content == "" || table_name == "" || condition == "")                    {                        Console.WriteLine("语法错误 " + sql);//打印错误信息               }                }    MySqlCommand cmd = new MySqlCommand(sql, sql_Test);                MySqlDataAdapter mda = new MySqlDataAdapter(cmd); //获取结果集                mda.Fill(dt);            }            else            {                Console.WriteLine("数据库未连接!");//打印信息            }            return dt;        }    }}

来源地址:https://blog.csdn.net/DXuexue/article/details/130154394

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-数据库
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯