C# ADO.NET
C# ADO.NET
Database Connection
How to connect SQL Server
(Example) By: Barbara Thompson
10/11/2021
12/4/2021 C# - QL CONNECTION 1
In this C# sql connection
tutorial, you will learn-
Fundamentals of Database connectivity
How to connect C# to Database
Access data with the SqlDataReader
C# Insert Into Database
Updating Records
Deleting Records
Connecting Controls to Data
C# DataGridView
When you click on “connect” button, from the output, you can see
that the database connection was established. Hence, the
message box was displayed.
12/4/2021 C# - SQL CONNECTION 15
Access data with the SqlDataReader
To showcase how data can be accessed using C#, let us assume that we have the
following artifacts in our database.
1. A table called demotb. This table will be used to store the ID and names of
various Tutorials.
2. The table will have 2 columns, one called “TutorialID” and the other called
“TutorialName.”
3. For the moment, the table will have 2 rows as shown below.
TutorialID TutorialName
1 C#
2 ASP.Net
Let’s change the code in our form, so that we can query for this data and display the
information via a Messagebox. Note that all the code entered below is a continuation of
the code written for the data connection in the previous section.
When the above code is set, and the project is run using Visual Studio, you will get the below
output. Once the form is displayed, click the Connect button.
Output:-
2.The next step is to actually define the SQL statement which will be used against our database. In our case, we are issuing
an insert statement, which will insert the record of TutorialID=1 and TutorialName=VB.Net
3.Next, we create the command object which is used to execute the SQL statement against the database. In the SQL
command, you have to pass the connection object and the SQL string
4.In our data adapter command, we now associate the insert SQL command to our adapter. We also then issue the
ExecuteNonQuery method which is used to execute the Insert statement against our database. The ‘ExecuteNonQuery’
method is used in C# to issue any DML statements against the database. By DML statements, we mean the insert, delete,
and update operation. In C# , if you want to issue any of these statements against a table, you need to use the
ExecuteNonQuery method.
5.We finally close all the objects related to our database operation. Remember this is always a good practice.