New to C# programming, I'd like to be able to access MySQL
Databases.
I know MySQL connector/NET
and MySQL for Visual Studio
are required for C# development.
Do I need to install them into my app?
Is it possible I can just release the connector DLL with the program?
Update:
Are both of them required for the end-user or just the connector?
Is there anything else they would need?
Show MySQL Databases The most common way to get a list of the MySQL databases is by using the mysql client to connect to the MySQL server and run the SHOW DATABASES command. If you haven't set a password for your MySQL user you can omit the -p switch.
Install Oracle's MySql.Data
NuGet package.
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(); } } }
Example:
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(); }
You can use Package Manager to add it as a package and it is the easiest way. You don't need anything else to work with a MySQL database.
Or you can run this command in Package Manager Console:
PM> Install-Package MySql.Data
NuGet MySql.Data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With