C#连接mysql数据库

C#连接mysql数据库

一、说明

C#连接mysql数据库有多种方法,这里详细说明采用Mysql.Data.dll组件方法。

Mysql.Data.dll下载地址http://pan.baidu.com/s/1nt0n0RB

将该程序集添加至程序引用中。

二、程序

集成在一个类中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
using System.Windows.Forms;


namespace ShoppingServer
{
    public class DBHelper
    {
        /// <summary>         
        /// 得到连接对象         
        /// </summary> 
        /// <returns>MySqlConnection</returns> 
        public MySqlConnection GetConn()
        {
            String constr = "Database='shoppingsystem';UserId='root';DataSource='localhost';Password='1152734'";
            MySqlConnection mysqlconn = new MySqlConnection(constr);
            return mysqlconn;
        }
    }
    public class SQLHelper : DBHelper
    {
        /// <summary>         
        /// 查询操作         
        /// </summary> 
        /// <param name="sql"></param>         
        /// <returns>DataTable</returns> 
        public DataTable Selectinfo(string sql)
        {
            MySqlConnection mysqlconn = null;
            MySqlDataAdapter sda = null;
            DataTable dt = null;
            try
            {
                mysqlconn = base.GetConn();
                sda = new MySqlDataAdapter(sql, mysqlconn);
                dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return dt;
            }
        }
        /// <summary>         
        /// 增删改操作        
        /// </summary> 
        /// <param name="sql">sql语句</param>         
        /// <returns>执行后的条数</returns>         
        public int AddDelUpdate(string sql)
        {
            MySqlConnection conn = null;
            MySqlCommand cmd = null;
            try
            {
                conn = base.GetConn();
                conn.Open();
                cmd = new MySqlCommand(sql, conn);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                return i;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -1;
            }
        }
    }
}

主程序调用:

 SQLHelper helper = new SQLHelper(); 
 private void MyForm_Load(object sender, EventArgs e)
        {
            string name = "";
            string sql = string.Format("select * from shoppingsystem.goods");
            DataTable dt = helper.Selectinfo(sql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //从数据库得到stuname 字段的值 
                name += (string)dt.Rows[i]["name"] + "\r\n";
            }
            //把得到的值放到文本框中             
            this.richTextBox1.Text = name;
        }

private void btnAdd_Click(object sender, EventArgs e)
        {
            string sql = string.Format("insert into userinfo values('{0}','{1}')", this.txtname.Text, txtpwd.Text); 
            int i = helper.AddDelUpdate(sql); if (i > 0)
            {
                MessageBox.Show("增加成功");
            }
        }

以下是C#连接MySQL数据库的步骤和示例代码: 1. 首先需要安装MySQL Connector/NET,可以在MySQL官网下载安装包进行安装。 2. 在C#项目中添加对MySQL Connector/NET的引用。 3. 在代码中使用以下代码进行连接: ```csharp using MySql.Data.MySqlClient; string connStr = "server=127.0.0.1;port=3306;user=root;password=power123;database=my_data;"; MySqlConnection conn = new MySqlConnection(connStr); try { conn.Open(); Console.WriteLine("MySQL连接成功!"); } catch (MySqlException ex) { Console.WriteLine("MySQL连接失败:" + ex.Message);} finally { conn.Close(); } ``` 其中,`connStr`是连接字符串,包含了MySQL服务器的IP地址、端口号、用户名、密码和数据库名。`MySqlConnection`是MySQL Connector/NET提供的连接对象,通过`Open()`方法打开连接,`Close()`方法关闭连接。 4. 连接成功后,可以使用`MySqlCommand`对象执行SQL语句,例如: ```csharp string sql = "SELECT * FROM my_table"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetString(0) + "\t" + reader.GetString(1)); } reader.Close(); ``` 其中,`sql`是要执行的SQL语句,`MySqlCommand`是MySQL Connector/NET提供的执行对象,通过`ExecuteReader()`方法执行SQL语句并返回一个`MySqlDataReader`对象,通过`Read()`方法读取查询结果。 5. 可以使用`DataGridView`控件显示查询结果,例如: ```csharp string sql = "SELECT * FROM my_table";MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn); DataSet ds = new DataSet(); adapter.Fill(ds, "my_table"); dataGridView1.DataSource = ds.Tables["my_table"]; ``` 其中,`MySqlDataAdapter`是MySQL Connector/NET提供的数据适配器对象,通过`Fill()`方法将查询结果填充到`DataSet`对象中,然后将`DataSet`对象中的表绑定到`DataGridView`控件上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值