VS2017C#连接MySQL数据库及添加删除修改

技术分享 学习心得 2020-03-26 阅读:147

很多用C#的对于MySQL数据库的连接相信都比较头痛,那么c#如何连接MySQL呢?接下来请跟着小编走

1.首先从网上下载mysql.data.dll

20200324170308229.jpg

 
20200324170336971.jpg

20200324170354200.jpg
 

20200324170410253.jpg

2.打开现有的项目工程或者新建一个C#的项目,找到引用,点击右键选择添加引用如图

20200324170648638.png
 

接下来就可以进行码了

(1)码什么都得告诉程序加入的文件名才能调用

using MySql.Data.MySqlClient;//调用MySQL动态库

(2)建立连接:

MySqlConnectionsqlCon= new MySqlConnection("Database=数据库名字;Data Source=服务器的ip地址;User Id=用户名;Password=用户密码");

或者:

MySqlConnectionsqlCon= new MySqlConnection("server=服务器的ip地址;user id=用户名;password=用户密码;database=数据库名字");

或者:
 string M_str_sqlcon = "server=服务器ip地址;User Id=用户名;password=用户密码;Database=数据库名字";//根据自己的设置
 MySqlConnection sqlCon = new MySqlConnection(M_str_sqlcon);

注释:server=服务器ip地址;User Id=用户名;password=用户密码;Database=数据库名字,这几个的顺序可以调换,只要对准每个字符串和标识符就好了。

(3)执行sql命令:
//设置查询命令
MySqlCommand  mycmd= new MySqlCommand("select * fromt_dept whereTITLElike '%p%'", sqlCon);

 

完整代码:

using System;
using System.Configuration;
using MySql.Data.MySqlClient;
/// <summary>
/// TestDatebase 的摘要说明
/// </summary>
public class TestDatebase
{
    public TestDatebase()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    public static void Main(String[] args)
    {
        MySqlConnection mysql = getMySqlCon();
        //查询sql
        String sqlSearch = "select * from student";
        //插入sql
        String sqlInsert = "insert into student values (12,'张三',25,'大专')";
        //修改sql
        String sqlUpdate = "update student set name='李四' where id= 3";
        //删除sql
        String sqlDel = "delete from student where id = 12";
        //打印SQL语句
        Console.WriteLine(sqlDel);
        //四种语句对象
        //MySqlCommand mySqlCommand = getSqlCommand(sqlSearch, mysql);
        //MySqlCommand mySqlCommand = getSqlCommand(sqlInsert, mysql);
        //MySqlCommand mySqlCommand = getSqlCommand(sqlUpdate, mysql);
        MySqlCommand mySqlCommand = getSqlCommand(sqlDel, mysql);
        mysql.Open();
        //getResultset(mySqlCommand);
        //getInsert(mySqlCommand);
        //getUpdate(mySqlCommand);
        getDel(mySqlCommand);
        //记得关闭
        mysql.Close();
       String readLine = Console.ReadLine();
    }
    /// <summary>
    /// 建立mysql数据库链接
    /// </summary>
    /// <returns></returns>
    public static MySqlConnection getMySqlCon()
    {
        String mysqlStr = "Database=test;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";
        // String mySqlCon = ConfigurationManager.ConnectionStrings["MySqlCon"].ConnectionString;
        MySqlConnection mysql = new MySqlConnection(mysqlStr);
        return mysql;
    }
    /// <summary>
    /// 建立执行命令语句对象
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="mysql"></param>
    /// <returns></returns>
    public static MySqlCommand getSqlCommand(String sql,MySqlConnection mysql)
    {
        MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql);
        //  MySqlCommand mySqlCommand = new MySqlCommand(sql);
        // mySqlCommand.Connection = mysql;
        return mySqlCommand;
    }
    /// <summary>
    /// 查询并获得结果集并遍历
    /// </summary>
    /// <param name="mySqlCommand"></param>
    public static void getResultset(MySqlCommand mySqlCommand)
    {
        MySqlDataReader reader = mySqlCommand.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    Console.WriteLine("编号:" + reader.GetInt32(0) + "|姓名:" + reader.GetString(1) + "|年龄:" + reader.GetInt32(2) + "|学历:" + reader.GetString(3));
                }
            }
        }
        catch (Exception)
        {
            Console.WriteLine("查询失败了!");
        }
        finally
        {
            reader.Close();
        }
    }
    /// <summary>
    /// 添加数据
    /// </summary>
    /// <param name="mySqlCommand"></param>
    public static void getInsert(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            String message = ex.Message;
            Console.WriteLine("插入数据失败了!" + message);
        }
 
    }
    /// <summary>
    /// 修改数据
    /// </summary>
    /// <param name="mySqlCommand"></param>
    public static void getUpdate(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            String message = ex.Message;
            Console.WriteLine("修改数据失败了!" + message);
        }
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="mySqlCommand"></param>
    public static void getDel(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            String message = ex.Message;
            Console.WriteLine("删除数据失败了!" + message);
        }
    }
}

visualstudio连接mysql插件

链接: https://pan.baidu.com/s/1dgUF8x_LCPSqIRUdFHEhAQ
提取码: w157

版权声明

本文基于《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
文章链接:https://hiai.top/archives/347.html (转载时请注明本文出处及文章链接)

如果觉得我的文章对你有用,请随意赞赏

0条评论