如何连接到MySQL数据库?
我很新的C#编程,但希望能够访问MySQL数据库(没有MS SQL的钱)
但是我有一个问题, 我知道你需要有用于开发C#应用程序的“MySQL connector / NET”和“MySQL for Visual Studio”,但安装应用程序的人是否也需要它们? (是否有可能我可以释放连接器DLL与程序?)
谢谢
编辑:他们都需要最终用户或只是连接器? 还有什么需要的吗?
using MySql.Data; using MySql.Data.MySqlClient; namespace Data { public class DBConnection { private DBConnection() { } private string databaseName = string.Empty; public string DatabaseName { get { return databaseName; } set { databaseName = value; } } public string Password { get; set; } private MySqlConnection connection = null; public MySqlConnection Connection { get { return connection; } } private static DBConnection _instance = null; public static DBConnection Instance() { if (_instance == null) _instance = new DBConnection(); return _instance; } public bool IsConnect() { bool result = true; if (Connection == null) { if (String.IsNullOrEmpty(databaseName)) result = false; string connstring = string.Format("Server=localhost; database={0}; UID=UserName; password=your password", databaseName); connection = new MySqlConnection(connstring); connection.Open(); result = true; } return result; } public void Close() { connection.Close(); } } }
例:
var dbCon = DBConnection.Instance(); dbCon.DatabaseName = "YourDatabase"; 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); } }
您可以使用软件包pipe理器将其添加为包,这是最简单的方法。 你不需要任何其他工作与MySQL数据库。
也可以在软件包pipe理器控制台中运行以下命令
PM> Install-Package MySql.Data
NUGET Mysql.Data
看下面的代码,我试了一下,发现:而不是写DBCon = DBConnection.Instance();
你应该把DBConnection DBCon - new DBConnection();
(这对我有效)
而不是MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection());
你应该把MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection());
(这是缺less的d)
private void Initialize() { server = "localhost"; database = "connectcsharptomysql"; uid = "username"; password = "password"; string connectionString; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";"; connection = new MySqlConnection(connectionString); }
试试这个连接
string Server = "server"; string UserName = "username"; string Password = "password"; string Database = "database"; string Port = "port"; public readonly string config = string.Format("Server = {0}; Port = {1}; Database = {2}; Uid = {3}; Pwd = {4}; pooling = true; Allow Zero Datetime = False; Min Pool Size = 0; Max Pool Size = 200; ", Server, Port, Database, UserName, Password); using (var con = new MySqlConnection { ConnectionString = config }) { con.Open(); }