Making DB Connection (MYSQL) Using C# – Devstringx
In this blog going to explain how to connect the MYSQL database to C#.
First, ensure you have downloaded and introduced the MySQL Connector/NET from the MySQL official site. In this blog, I will utilize the Connector/NET form 6.1.
To interface MySQL information base to a C# application, MySQL gives a progression of classes in the MySQL Connector/Net. All the correspondence between a C# application and the MySQL server is directed through a MySqlConnection Object. Along these lines, before your application can speak with the server, it should launch, arrange, and open a MySqlConnection object.
MySQL is a main open-source data set administration framework. It is a multi-client, multithreaded information base administration framework. Download MySQL Connector/Net
Download MySQL Connector/Net
It can be downloaded from the Mysql developer website https://dev.mysql.com/downloads/ free of cost.
Add Reference
Before we start to connect our application to MySql Database, We need to add the MySQL Reference in our project. To do this, right-click on the project name, choose Add Reference, then choose “MySql.Data” from the list.
After that under the reference right click on System.Data.SqlXml
And then select copy local value as “true”
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test_Automation { internal class DatabaseConnectionwithCsharp { // Main Method static public void Main(String[] args) { string server = "localhost"; string database = "testdb"; string username = "root"; string password = "password"; string connectionstring = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + username + ";" + "PASSWORD=" + password + ";"; MySqlConnection connection = new MySqlConnection(connectionstring); connection.Open(); } } }
Explanation of variables declared in the program
- Server: It indicates where our server is hosted, in our case, it’s localhost.
- Database: It is the name of the database we will use, in our case it’s the database we already created earlier which is testdb.
- Username: It is our MySQL username.
- Password: It is our MySQL password.
- Connectionstring: It contains the connection string to connect to the database, and will be assigned to the connection variable.
- Connection.Open(); : It opens the Connection.
Conclusion:
In this Blog, I demonstrated the Making connection between the MYSQL database to C#.