欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[C#]C#连接MySQL方法

程序员文章站 2022-06-12 17:13:15
...

1.需要添加引用:MySql.Data.dll,可以网上搜索下载;

2.SqlHelper写法:

此处connStr写死了,实际上应该写在配置文件中,再读取;写法如下:

public static readonly string connStr = "Server=192.168.0.1;Port=2222;Database=TEST;Uid=root;Pwd=123";

public static int ExecuteNonQuery(string sql, params MySqlParameter[] parameters)
{
    using  (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        using (MySqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.Parameters.AddRange(parameters);

            return cmd.ExecuteNonQuery();
        }
    }
}

public static Object ExecuteScalar(string sql, params MySqlParameter[] parameters)
{
    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        using (MySqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.Parameters.AddRange(parameters);

            return cmd.ExecuteScalar();
        }
    }
}

public static DataTable ExecuteTable(string sql, params MySqlParameter[] parameters)
{
    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        using (MySqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.Parameters.AddRange(parameters);

            DataSet dataSet = new DataSet();
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);

            adapter.Fill(dataSet);
            return dataSet.Tables[0];
        }
    }
}

public static DataSet ExecuteDataSet(string sql, params MySqlParameter[] parameters)
{
    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        using (MySqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.Parameters.AddRange(parameters);

            DataSet dataSet = new DataSet();
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);

            adapter.Fill(dataSet);
            return dataSet;
        }
    }
}

 

相关标签: C# MySQL