c# - 如何连接MySQL数据库?

标签 c# mysql nuget-package mysql-connector

C# 编程新手,我希望能够访问 MySQL 数据库。

我知道 C# 开发需要 MySQL Connector/NETMySQL for Visual Studio
我需要将它们安装到我的应用程序中吗?
我是否可以只用程序释放连接器 DLL?

更新:
最终用户需要两者还是仅连接器需要?
他们还需要什么吗?

最佳答案

安装 Oracle 的 MySql.Data NuGet 包。

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

示例:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

关于c# - 如何连接MySQL数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840504/

相关文章:

c# - 获取在异步方法中调用方法的类的类类型

PHP创建多个Word文档并允许下载

ssas - 适用于 asp.net core 的 ADOMD nuget 包

c# - BASS.net C# : What does spectogram image represent that outputted by CreateSpectrum3DVoicePrint Method?

c# - 异步导致调试器跳转

php - 变音符号敏感搜索 PHP

nuget - 为什么 nuget 将 1.2.3.4 视为稳定(发布)版本?

c# - 无法在 Visual Studio 2012 中安装任何 NuGet

c# - ASP.NET MVC Razor 获取文本框值

php - 无法连接到数据库