M. Niyazi Alpay
M. Niyazi Alpay
M. Niyazi Alpay

I've been interested in computer systems since a very young age, and I've been programming since 2005. I have knowledge in PHP, MySQL, Python, MongoDB, and Linux.



Database Connection in C#

In C#, for SQLServer connection, we need to call SqlClient namespace (using System.Data.SqlClient;), or for another database, we call the required namespace. For MySQL, if the .NET connector is installed, we use using MySql.Data.MySqlClient;.

Connection commands: SqlConnection for SQLServer, and MySqlConnection if we are using MySQL. Notice that only the My prefix is added to the command.

I will continue my example with MySQL.

MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=root; database=cryptograph");

We create an object named connection with the MySqlConnection command, and then we write our database information inside the parentheses after the equality sign.

Server is where our database is located, userid is the username of the database user, password is the password of the database user, and database defines the name of our database.

Now, we have only defined an object named connection, we have not opened the connection yet. To open the connection, we use the command connection.Open();. In this usage, if there is a problem with the connection, the program will throw an error and stop working. In such cases, we use error control commands like try-catch.

try {
   MessageBox.Show("Connection opened");
catch (Exception error) {

If the connection is opened, it will show a message box saying Connection opened, and if there is an error with the connection, it will show the error message along with the error code.

To close the connection, we need to use connection.Close(); command.

C# Database Connection

You can download the example file from here.

You may also want to read these

There are none comment

Leave a comment

Your email address will not be published. Required fields are marked *