gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:00:34 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com