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/37268883/

相关文章:

mysql - 在 MySQL 中如何编写比子查询更好地连接两个表的 SQL?

mysql - 按两列为每个用户组选择 3 条记录

c# - 如何向 SQL Server 发出 LINQ 查询以检查列值是否以单词开头?

c# - C# 应用程序中 where 子句中的未知列

mysql - 在mysql中选择最大记录

visual-studio - 您如何知道 Nuget 包是否已签名

visual-studio-2010 - 缺少包导致 NuGet 包还原失败

c# - 其他网络上的 WCF UDP 发现

c# - 我应该如何在启动时在 ConfigurationServices ASP.NET Core 2.0 中使用 appsettings.json 配置键/值?

nuget-package - 测试错误 :Could not load file or assembly 'CaSTLe. 核心,版本=4.0.0.0,文化=中性