Перейти к содержимому

Как подключить базу данных sql к visual studio

  • автор:

Создаем проект базы данных в Visual Studio 2019

В настоящее время базы данных (БД) являются проблемой для разработчиков, и это одна из самых сложных задач в любом проекте ПО для управления изменениями БД и синхронизации этих изменений. Для решения этой проблемы в Visual Studio имеются проекты баз данных SQL. Можно с легкостью разрабатывать, управлять, сравнивать и развертывать изменения базы данных с помощью Visual Studio.

А также можем отслеживать изменения всех объектов БД через систему контроля версий. Visual Studio Database Project предоставляет гибкие возможности для создания нового проекта базы данных из существующей БД с помощью нажатия на кнопку или возможность создания проекта базы данных с нуля.

Итак, поехали

Запускаем Visual Studio 2019, выбираем Create a new project, потом выбираем SQL Server Database Project.

Введем название базы данных и выберем место расположения файла.

После чего щелкаем по кнопке Create. А теперь правой кнопкой мыши щелкаем по проекту SampleDB и из появившейся меню выбираем Add > Table.

Присваиваем имя таблице – “Student” и щелкаем по кнопке Add.

После того, как добавили таблицу, появится окно конструктора таблицы. Здесь мы можем добавлять столбцы с типом данных.

Добавим несколько столбцов в эту таблицу. Мы увидим, что сгенерируется скрипт в нижней части окна и сохраняется схема таблицы.

Теперь пора опубликовать базу данных в SQL Server

Щелкаем правой кнопкой мыши в окне Solution Explorer по проекту базы данных. В появившемся меню выбираем Properties. В параметрах проекта выбираем версию SQL Server.

Кроме того, мы можем изменять подключение по умолчанию на вкладке Debug Щелкаем по кнопке Edit.

Изменяем свойства соединения в соответствии с параметрами ПК. Введем имя сервера, имя пользователя, пароль и выберем базу данных. Потом щелкаем по кнопке OK. Если есть проверка подлинности Windows, то не нужно указывать имя пользователя и пароль. Нам нужно только имя сервера и база данных.

Не забываем сохранять все изменения. А теперь щелкаем правой кнопкой мыши на проекте БД и выбираем Publish… Редактируем настройки Target Database.

Введем свойства подключения, такие как – если это проверка подлинности SQL Server, то указываем имя сервера, имя пользователя, пароль и выбираем базу; а если это аутентификация Windows, то указываем имя сервера и базу данных.

После чего мы жмем на кнопку Publish. Немного подождем, пока БД не будет опубликована.

Теперь запускаем SQL Server Management Studio и проверяем, есть ли база данных SampleDB или нет.

Вывод

В этой статье мы узнали, как создать проект базы данных в Visual Studio 2019 и публиковать ту же БД в SQL Server 2017.

C# Connect To MySQL In Visual Studio 2019

Ojash Shrestha

In this article, we’ll learn to connect the MySQL Database with the C# .NET Framework application in Visual Studio 2019. This is a foundational hands-on article that will help beginners to connect a widely used freely available database like MySQL in C# through other freely available tools. This article doesn’t require any paid applications or software.

Step 1

First of all, let us start with the installation of XAMPP. XAMPP makes it possible to create a local server with Apache and MySQL database with more other features.

Once the installation is done, the control panel should look something like this.

Step 2

Click on Start on Apache, MySQL, and FileZilla. The buttons turn the labels into Stop.

Step 3

Open your browser and type, localhost/phpmyadmin/

The page will look something like as follows. This is where the database can be accessed, viewed and instructions can be performed right away. This is the location to access, the MySQL database.

Step 4

Click on Databases.

Now, Under Create Database, Type the name of the new database we are going to create.

Type, TestDB, leave the Collation as it is, and then click on Create.

Step 5

The Database TestDB has now been created. Let us create a Table now.

Step 6

Run the SQL Query

Step 7

The Table has been created with an empty set and zero rows.

Step 8

You can view the table on the database from the Structure Option in the bar.

Click to browse and see the contents of the table.

Step 9

Now, let us install Visual Studio 2019. The Community Edition is free and can be accessed from the Microsoft Official Website.

Once installed, the Visual Studio Installer can be opened. Now, click on Launch.

Step 10

Click on Create a New Project.

Create the project for Windows Forms App in C#, .NET Framework with Solution name of your choice.

Step 11

You can see the solution Explorers as shown below with the references and resources all setup for the Framework.

Step 12

Now, let us go to Tools on the Menu Bar and select Connect to Database. There are numerous but no MySQL Database Option. This can be resolved by installing the MySQL Connector and MySQL for Visual Studio.

Step 13

Next, we need to install MySQL Connectors and MySQL for Visual Studio. Visit the following sites to obtain the download file for the respective installations, ADO.NET Driver for MySQL (Connector/NET) and MySQL Installer for Visual Studio.

Download the ADO.NET Driver for MySQL (Connector/NET) and MySQL Installer for Visual Studio 1.2.10 — Microsoft Windows — x86 MSI Installer.

Step 14

Once the MySQL Installations are done, restart Visual Studio 2019.

Step 15

Now, go to Solution Explorer. Right click on the project, click on Add and select the Reference.

Step 16

Click on MySql.Data and MySql.DataEntityFramework for EF6 primarily. And then Click on Ok.

Step 17

Now, let us go back to the Server Explorer. Double-Click on Data Connections and Choose Add Connections. You’ll be taken to Choose Data Source Option.

Under Data Source, Now, we can see the MySQL Database option. This wasn’t there primarily when we hadn’t installed MySQL Connector and MySQL for Visual Studio.

Step 18

Now, Click on Continue. The Server Name, User Name, Password, and Database Name are to be filled in.

Remember, this is the same as that of your database on the localhost/phpmyadmin

I’ve put in my Server name which is “localhost”, a User name that is “root” and my password. Remember, above we made the Database TestDB for this very experiment. Here, we can use the lowercase name “testdb”.

Click on Test Connection and as the success is prompted, choose OK.

Note
In case any issues occur that prompt an error for database connection, choose the Advanced option and under the SSL Mode, Choose None. This would solve the error.

Step 19

Now, we can see the localhost(testdb) database on our DataConnections with its tables. Remember, the PhoneBook table that we created earlier in phpmyadmin? See, it’s here now.

Step 20

Right Click on the table, and we can see the options for Trigger, Table Script Generation, Query, Designing, and Retrieving Data.

When we choose the generate Table Script, the following script will pop up.

Similarly, if we choose to retrieve data, the data can be seen. Here, since, we haven’t entered any data, NULL is seen.

Step 21

To test, if the connection has been made, let’s go back to localhost/phpmyadmin and insert some data on the table PhoneBook.

When we reload, we can see the NULL has now changed to numerous data on Id, Name, and MobileNo in the phonebook.

How to use C# with SQL

In this post we’ll look at how to use C# with SQL. In this tutorial, we will discuss the process for creating a very simple C# console application that connects to a SQL Server database. You will learn the most basic steps needed to use C# with SQL. You will see how we can gather some basic information from the user and use it to run T-SQL commands behind the scenes to retrieve or update data in the database.

When it comes to SQL Server databases, I would say most of the time, your end users will NOT be running queries or updating data directly within SQL Server Management Studio. They will most likely be using a user-friendly software application that ultimately accesses the database and does the data retrieval or updating behind the scenes.

If you’re new to SQL, don’t forget to check out our article to Learn SQL Server.

We will discuss the following topics in this tutorial:

Install Visual Studio 2019 Community and create an empty C# project

We will be using the latest-and-greatest free version of Microsoft Visual Studio to create our simple C# console application: Visual Studio 2019 Community.

In previous years, the free edition of Visual Studio has been called ‘Express‘. Recently, Microsoft decided to rename their free edition to ‘Community‘. So understand they are one-in-the-same.

Here is what the download page looks like:

C Sharp Connect to SQL Server VS download

Just click the Download Community 2019 link to start the download. This will download an .exe file starting with the name “vs_community“.

Installing Visual Studio Community 2019

Once that executable finishes downloading, double click on it to start the installation.

You’ll first see the Visual Studio Installer start up:

C Sharp Visual Studio Installer

When it’s loaded, you’ll need to specify what “workload” you want to initially install with Visual Studio. You’ll pick .NET desktop development. The C# language , in case you didn’t know, is a .NET language:

C Sharp Visual Studio NET workload

Then, the installation process will begin!:

C Sharp Visual Studio Installer progress

Notice the “Start after installation” checkbox is enabled. This will start Visual Studio Community automatically after the installation process is complete.

Setting up a C# project

Before we create our project, the first question we’re asked is the color theme we want Visual Studio to use. I like the regular Blue theme, but many people like the Dark theme. Pick the one you think you’ll like!:

C Sharp Visual Studio Color theme

Then click Start Visual Studio.

You’ll be presented with a Get Started screen, where you’ll want to select Create a new project:

C Sharp Visual Studio Create Project

On the “Create a new Project” screen, we’re going to pick the Console Application option that outlines the C# language, as shown here:

C Sharp Visual Studio create a new project

Then click Next.

We’re almost there. The next step is to name our C# project. Let’s call it SimpleSQLProject:

C Sharp Visual Studio Project Name 2

When you outline a Project Name, the Solution Name also updates. You can change it if you want to.

Also, the Location is given a default path. Again, you can change that if you want to. I’m just going to leave it alone.

Then, hit Next!

It will quickly ask you what version of .NET you want to use. Go ahead and pick .NET 5.0 if it’s available, then click Create.

C Sharp NET Version

That’s it! We have an empty project ready to use C# with SQL:

C Sharp Empty Project

Gotta love the classic “Hello world” console message. These are every programmer’s first words spoken, you see.

Add the System.Data.SqlClient namespace to your C# project

As I subtly hinted at earlier, the key to linking a C# application to a SQL Server database is to use the System.Data.SqlClient namespace. This namespace contains all the classes and functions we need to make all our dreams come true.

Let’s add this namespace to our SimpleSQLProject project.

In Visual Studio, navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution

C Sharp Project NuGet

This will open a new window where you can search for the System.Data.SqlClient namespace:

C Sharp System Data SqlClient installation

Here’s a rundown on what to do on this page:

  1. Make sure you are on the Browse tab, then type the name of the namespace we want, System.Data.SqlClient. It should appear as the first result.
  2. Enable the checkbox next to the project you want to add the namespace to (we only have one project, SimpleSQLProject).
  3. Click Install

Important! Don’t skip this step, or else you can use C# with SQL. The System.Data.SqlClient reference is crucial!

IF YOU DON’T GET ANY RESULTS WHEN SEARCHING FOR THE System.Data.SqlClient NAMESPACE:

You might need to update the web location where the namespaces are searched. Navigate to Tools -> NuGet Package Manager -> Package Manager Settings:

Package Manager Settings

In the “Options” window that appears, look in the Package Sources option. Make sure the Source field contains the following URL: https://api.nuget.org/v3/index.json

Package source correct location

I encountered this issue and it nearly drove me crazy. Hopefully I just saved you a couple hours’ worth of Googling and frustration. You’re welcome.

We can double-check that our namespace is part of the project. Look at the properties of the project in the Solution Explorer, under Dependencies -> Packages:

solution explorer seeing new package

The “using” clause

The last thing we need to do is outline a using clause in our source code. Here’s the syntax:

A moment ago, we added the namespace to the project, but we didn’t actually say we wanted to use it yet. The using clause does just that:

using namespace in code

We’re on our way.

Setting up a SQL Server connection string

To use C# with SQL, you’ll need to “connect” to the database. Our C# application needs to know the SQL Server connection details in order to work properly, obviously. Those details are outlined in something called a connection string.

The connection string contains details like:

  • Name of the SQL Server
  • Database name
  • Login credentials

It contains everything the C# application needs to find and connect to the database.

So then the question becomes: How do I create a SQL Server connection string?

Creating a SQL Server connection string using a UDL file

We can create something called a UDL file to help us create the SQL Server connection string. Here are the simple steps:

  1. On the desktop (or any folder location, really) right click and choose New -> Text Document.
  2. The name of the document doesn’t matter, but you should change the extension of the document from .TXT to .UDL. You’ll get a prompt asking if you are sure. We are, in fact, sure.
  3. Right click the new .UDL file and select Open With -> OLE DB Core Services. This will open the following “Data Link Properties” window:

You’re going to fill out this form with the connection information for your SQL Server and database. Here is an example of the content of my UDL file:

c# with SQL - udl file example

My SQL Server is called “BEETLEJUICEPC\SQLEXPRESS01“, the name of the database is “Dealership“, and I’m choosing to connect to them using my Windows credentials. If you would rather connect to the SQL Server by outlining a username and password (maybe the SA account, for example), you can do that.

When you’ve outlined everything, click Test Connection to make sure it works!:

test connection successful

Once you’ve verified the connection is valid, click OK to close the UDL form.

Writing out the connection string to a file

Next, we can open the same UDL file within a text editor (like Notepad or Notepad++) and see the connection information there in plain text format.

Right click the UDL file and choose Open With -> Notepad. The document will open in Notepad and you will see your new connection string!:

connection string info

Yours might look slightly different from mine, but you should see the name of your SQL Server and database. If you chose to login using a username and password, you would see that, too.

Awesome, so now we have the connection string.

We should copy that string to it’s own file, then put that file in the same folder location as our project. It doesn’t need to be in that folder location, but that seems like the best place for it.

Remember earlier when we created the C# project, it outlined the default location where the project would be saved to. I’ll just put the new ConnectionString.txt file there.

(I need to emphasize that this ConnectionString.txt file doesn’t need to exist, but later we’ll see why it’s a really good idea to have it)

Important: When you copy the connection string to this ConnectionString.txt file, you need to add the words ‘Data Source =‘ to the front of it.

So the file will looks like this:

c# with SQL connection string info2

We’re on the home stretch.

Performing a SELECT statement from your C# program

Ok, let’s make a simple connection to the database.

But first, let’s actually create some data in our database. For our examples, we’re going to pretend we work at a used car dealership, and need a database to keep track of the vehicles in our inventory. We’re going to start with a table called Vehicles:

Notice the CarID column uses the IDENTITY property. This is useful for automatically populating the column with a new value on inserts.

Also notice the CarYear column is a SMALLINT data type. This data type can store a number as large as about 32,000, which is of course much more than we need, but it uses less space in memory than the INT data type, for example. You should always try to use the smallest data type to suit your needs.

Let’s populate the table with a single row:

Nice, here’s what the table ought to look like:

select all from vehicles

Writing a SELECT statement in the C# application

Let’s say our C# application is the tool our employees will use to gather details about cars in our inventory.

Let’s write a simple SELECT statement to return all the details of a vehicle with a specific CarID, provided by the user.

In SQL, we know that’s a simple line of code. Let’s say we want to see all the details of CarID = 1

carID one

But let’s see if we can mimic that in our C# with SQL application. Again, the difference is that the user will provide the CarID value of the vehicle for which they want details.

Back in the C# application, let’s write the line of code where we ask the user for their input (in the Main function):

We read what the user typed with a simple Console.ReadLine(). But let’s take that input and actually use it as a parameter to a new function dedicated to the task of running a SQL SELECT statement. We’ll call our new C# function doSelectStatement. Here is the call to it:

If you are a programmer, you’ll understand the importance of functions. We want to isolate tasks into their own code blocks.

Using the SqlConnection, SqlCommand, and SqlDataReader classes

Ok, so now we need to write the doSelectStatement C# function. We’ll start slow:

The first thing we need to put in this function a using block, which outlines a new SqlConnection object:

Notice the *connection string* part. We’re going to copy and paste our connection string here, in quotes:

Remember to put the ‘Data Source =‘ at the front of the connection string.

Notice if your SQL Server name contains a backslash (‘\‘), you need to escape it with a second backslash.

(Again, I might have saved you hours’ worth of Googling. You’re welcome.)

Ok, so the newConnection object is used to connect to the database. The next step is to create a SqlCommand object, passing our newConnection object to it:

The first parameter to the SqlCommand constructor is the actual SQL statement we want to fire. It’s just a string value. Notice how we append the CarID value. The second parameter is the newConnection object we created in the using block.

Then, you see how we need to actually open the connection by saying selectCommand.Connection.Open()

(Later, we’ll make sure to close the connection by saying the following: selectCommand.Connection.Close())

The next thing we need to do is actually execute the SQL statement and read its results into a SqlDataReader object.

The way we execute our SQL statement is by calling the ExecuteReader() function on the selectCommand object. Here’s the code:

Again, notice we need to write the result of that ExecuteReader() function to a SqlDataReader object, called sqlReader in our case.

It’s a good idea to perform this ExecuteReader() function in a try…catch block. You want to make sure any errors in your code are handled gracefully.

Printing the results of our query to the screen

Ok, so we successfully executed our SQL query, and we know its results are held in the sqlReader object. The next step is to just pull the information from that object.

Let’s just show you how it’s done, then we’ll discuss it:

The first thing you should do is double-check your sqlReader object to make sure there is actually something to read. This is accomplished with the simple if (sqlReader.Read()) code. We want to make sure the query actually returned something.

It would be bad if we attempted to read information from the sqlReader object if it was empty.

So then we call several ‘Get‘ functions. These ‘Get‘ functions will read column data from the result set of our query. As a parameter to these ‘Get‘ functions, we pass a number representing the column we want to get data from. The result set columns start with an index of 0.

Which ‘Get‘ function we use depends on the data type of the column for which we need to read data.

The different ‘Get’ functions

If the column we need to read contains a string value, we use the GetString() function. If the column is an integer, we might need to use either GetInt16() or GetInt32() or even GetInt64()

Which ‘Get‘ function you use will depend on the data type of the SQL column you’re reading from.

For example, if we want the data from the first column in our result set, we need to use the GetString function since that is a string column. As a parameter to the function, we pass the number of the column we want to get data from. Since we want the first column, and column numbers start with an index of 0, the call would be GetString(0).

The CarYear of our vehicle is the fourth column in our SELECT statement. If columns start with an index of 0, this would mean the CarYear is column number 3. But to pull integer information, we need to use a ‘GetInt‘ method. Since the CarYear column is a SMALLINT data type, we use the ‘GetInt16‘ method. So the whole call is GetInt16(3).

(And also, we need everything to be in a string format for the Console.WriteLine method, so we actually need to call the ‘ToString‘ method on the whole thing to convert the integer result to a string: GetInt16(3).ToString())

Again folks, which ‘Get‘ function we use depends on the data type of the column for which we need to read data. Take a look at the official Microsoft documentation on the SqlDataReader class to understand more about the different ‘Get‘ methods.

Folks, we’ve done it. Here is everything we have so far:

All we need to do is build the solution and run it.

Building and running our C# with SQL code

To build the solution, just right-click the solution in the Solution Explorer in Visual Studio and choose Build Solution (or just hit Ctrl+Shift+B on your keyboard):

build solution

Then to run the application, just navigate to Debug -> Start Without Debugging (or just hit Ctrl+F5 on your keyboard):

start without debugging

It will launch your console app:

enter car ID

Remember, we want the user to enter the ID of the car they want details for. We only have one car in our Vehicles table, and it has a CarID of 1. So let’s enter 1 and see if our getSelectStatement function works:

successful run using c# with SQL

Yep, it checks out.

Reading the connection string from file

Let’s think about something we did in our source code that might be considered bad practice.

We basically hard-coded our connection string information in the C# code. If that seems a bit unsafe, that’s because it is. What if it needs to change? Sure, you can change it easily, but what about the end user? They won’t have access to the source code, nor would they really know what they’re doing if they did!

For that reason, it would be better to read in the connection string information from a file. Remember when we saved our connection string to a file called ConnectionString.txt? Well, we can read from that file in our source code. It would be best to also create a separate function dedicated to getting the connection string. We’ll call it getConnectionString.

To read from a file (using the FileStream class) we need to include the System.IO namespace to our application. That is as simple as adding another ‘using‘ clause to the top of our code:

systemIO

Once that is there, we can write the following getConnectionString function:

Again, notice the double backslashes in the folder path.

This function returns the string value of the connection string outlined in the ConnectionString.txt file. So now, instead of hard-coding the connection string, we can just call our new getConnectionString() function to retrieve the connection string for us:

Much cleaner. And now, if we need to change the name of the SQL Server or the database, we can change it in the ConnectionString.txt file!

Doing an UPDATE statement in your C# program

Folks, the rest of this tutorial is going to be slight variations of what you have already learned. The process for running other SQL statements (like UPDATE, INSERT or DELETE) is very similar to running a SELECT statement using C# with SQL.

Let’s think about an UPDATE statement. For this example, let’s have the user actually type out what UPDATE statement they want executed in SQL.

Here’s a new block in the Main function of our code:

Let’s talk about how this function is the same as our previous function:

  1. We created a using block that outlines a SqlConnection object called updateConnection. And again, we called our handy getConnectionString() function to grab the connection string from our file.
  2. We create a SqlCommand object called updateCommand. In the constructor, we pass the SQL statement we want to run and the connection object. In this case, the SQL statement is what the user typed out (stored in the updateStatement parameter). Then we open the connection saying updateCommand.Connection.Open().
  3. Then we execute the query using ExecuteNonQuery().

That last point is worth talking about. The statement we’re running isn’t exactly a query, is it? We’re not extracting information when we do an UPDATE statement.

I suppose that’s why Microsoft decided to name the method ExecuteNonQuery. If we are, in fact, querying data, we use ExecuteReader like we saw when running the SELECT statement earlier.

The other thing about ExecuteNonQuery is that it returns the number of rows effected by the SQL statement. So if our query did successfully update one row, the return value from ExecuteNonQuery would be 1. This is why it’s a good idea to put the call to ExecuteNonQuery in an ‘if‘ statement. If the command updated at least one row, we know it worked.

One final thing to note is how we don’t have a SqlDataReader object. Remember, we’re not reading anything, right?

Testing an UPDATE statement from our C# application

Let’s test it out. Remember to build the solution before running the program.

After the SELECT statement work is done, we’re asked to type the UPDATE statement we want executed:

testing update 1

So, let’s type an UPDATE statement. For example: UPDATE Vehicles SET Model=’Cherokee’ WHERE CarID = 1

Here is that UPDATE statement ran from our program:

update console

Now if we check the data in SQL, we see it did, in fact, change:

update successful

INSERT data from your C# with SQL program

Again folks, we’re basically going to do similar work for INSERT statement. This time, we’ll ask the user to enter the information they would like inserted into the Vehicles table.

Here is the new block in our Main function:

We’re asking the user for everything:

  • VIN
  • Make
  • Model
  • Year
  • Mileage

We are going to pass all that information to the new doInsertStatement function. Speaking of:

Again folks, it’s more of the same:

  1. Get a connection using SqlConnection and our handy getConnectionString function.
  2. Create a new SqlCommand object that passes the SQL statement we want to run as a parameter
  3. Call ExecuteNonQuery, which returns the number of rows effected. If the INSERT statement succeeded, that means one row was effected.

Let’s test it out:

Now let’s check the data:

insert test successful

DELETE data from database from your C# program

You get the idea. More of the same.

Let’s have the user enter the CarID of the car they want to delete. Here’s the new code in the Main function:

Here’s the new doDeleteStatement function:

We already know the drill:

  1. Get a connection using getConnectionString
  2. Create SqlCommand object
  3. Call ExecuteNonQuery

Let’s test it out:

delete car

Let’s check the data. We ought to see that CarID # 2 is gone, which is the Ford F150 we added earlier:

result set after delete

Final thoughts

I hope this tutorial helped you understand how to use C# with SQL by successfully connecting a SQL Server database to a C# application.

We’ve learned how to both read and write data to a database via a C# application. It’s all possible through the use of the System.Data.SqlClient namespace.

Your next steps should be to play around with this program. Write your own functions, add more error handling, think about how to reduce repeated code, make it more user friendly, etc. The changes you could make to this code are endless.

Also, take a look at the documentation for the System.Data.SqlClient class. There is a lot of great information for you to read through.

For your ultimate convenience, here is the entire C# code:

Want to learn more? Check out these related articles:

In addition, don’t forget to head on over to www.SimpleSQLTutorials.com where you’ll find more good stuff.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

MySQL Connection in C# (Console Application Example)

In previous article, I have explained about connecting to SQL server database in C# and have provided SQL server connection string examples, now in this article, I am providing working sample to connect to MySQL database in C# using Console application, you can use same code to connect to MySQL in ASP.NET, if needed.

Download and Install MySQL before using it

Before we begin, I hope you have downloaded and installed and MySQL in your PC, if not you can download and install MySQL first.

Once you have downloaded MySQL Installer from above link, open it, you will see windows like below

Select «Full» option and then click on «Next»

Then click on «Execute» in the next screen, to download and install all set up.

Note: It must install everything, including MySQL Server and you should also create default Username/Password to login into MySQL.

Once you have configured MySQL, download and install MySQL Workbench which help us to check data in our MySQL database easily. You will have to use above created Username/Password to login into MySQL database using MySQL workbench, you can connect to your MySQL and check sample database as shown in the below Gif Image.

Table which we will be using to show data, looks like below

Connecting to MySQL in C# using Visual Studio

Step 1: Once you have downloded and Installed MySQL with all of the above steps, let’s create a new Console Application project in Visual Studio, so open your Visual Studio, navigate to File-> New -> Project ->Select «Windows desktop» from left-pane and «Console Application(.NET framework)» from right-pane, give a name to your project and Click «OK»

Let’s Visual Studio generate the Console application template.

Step 2: Once Visual Studio Completes generation of template, you need add Reference of MySQL in your Visual Studio project, so navigate to «Solution Explorer» -> Right-Click «Add Reference»

Search for «MySQL» and add «MySQL.Data»

That’s it, we are done, we need to now write C# code to connect to MySQL, which is as shown below

To Insert New Row in MySQL database using C#

To Insert a new row in database, we will pass all rows values in SQL query and then execute Query, here is the complete C# code using Console Application.

As you can see out new row is added in the database, if we compare «Insert» code with «Fetch» Query code, this C# code is changed

Rest of the code remains same, i have explained most of the code using comments, so please read it carefully to understand each line of code.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *