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

相关文章:

c# - 用于缩进生成代码的 API

mysql - 错误: #1242 - Subquery returns more than 1 row in the query - MYSQL

python - SQLAlchemy - 如何获取1分钟以内的所有记录和最新记录的同一分钟?

nuget - 如何在nuget中创建像Microsoft.AspNetCore.All这样的元包(所有包的包)?

nuget - 如何从nuget包安装模板?

c# - ASP.NET:在某些情况下我应该担心内存泄漏吗? [C#]

c# - Type.GetMethod with a Generic overload - Get Generic MethodInfo without looping through all Methods

asp.net - 如何手动更新通过 NuGet 包安装的 jQuery UI?

c# - CSS + jQuery - 无法执行 .toggle() 并重复 jQueryTemplate Item [我必须警告你这有点让人不知所措]

php - 允许用户使用 mysql 为页面(id、节点等)添加书签的最有效方法是什么?