0% found this document useful (0 votes)
4 views

C# ADO.NET

C# ADO

Uploaded by

mohamedaliim61
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C# ADO.NET

C# ADO

Uploaded by

mohamedaliim61
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

C#

Database Connection
How to connect SQL Server
(Example) By: Barbara Thompson

MOHMED ABDULL AHI MOHAMUD


[email protected]

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

12/4/2021 C# - SQL CONNECTION 2


Fundamentals of Database connectivity
In working with databases, the following are the concepts which are common to
all databases.
1.Connection – To work with the data in a database, the first obvious step is the
connection. The connection to a database normally consists of the below-
mentioned parameters.
1. Database name or Data Source – The first important parameter is the database name to which the
connection needs to be established. Each connection can only work with one database at a time.
2. Credentials – The next important aspect is the username and password which needs to be used to
establish a connection to the database. It ensures that the username and password have the
necessary privileges to connect to the database.
3. Optional parameters – For each database type, you can specify optional parameters to provide
more information on how .net should handle the connection to the database. For example, one can
specify a parameter for how long the connection should stay active. If no operation is performed for a
specific period of time, then the parameter would determine if the connection has to be closed.

12/4/2021 C# - SQL CONNECTION 3



1.Selecting data from the database – Once the connection has been established, the
next important aspect is to fetch the data from the database. C# can execute ‘SQL’ select
command against the database. The ‘SQL’ statement can be used to fetch data from a
specific table in the database.
2.Inserting data into the database – C# can also be used to insert records into the
database. Values can be specified in C# for each row that needs to be inserted into the
database.
3.Updating data into the database – C# can also be used to update existing records into
the database. New values can be specified in C# for each row that needs to be updated into
the database.
4.Deleting data from a database – C# can also be used to delete records into the
database. Select commands to specify which rows need to be deleted can be specified in
C#.
Ok, now that we have seen the theory of each operation, let’s jump into the further sections
to look at how we can perform database operations in C#.

12/4/2021 C# - SQL CONNECTION 4


SQL Command in c#
SqlCommand in C# allow the user to query and send the
commands to the database. SQL command is specified by the
SQL connection object. Two methods are used, ExecuteReader
method for results of query and ExecuteNonQuery for insert,
Update, and delete commands. It is the method that is best for
the different commands.

12/4/2021 C# - SQL CONNECTION 5


How to connect C# to Database
We will see a simple Windows forms application to work with databases. We
will have a simple button called “Connect” which will be used to connect to
the database.
So let’s follow the below steps to achieve this

12/4/2021 C# - SQL CONNECTION 6



Step 1) The first step involves the
creation of a new project in Visual
Studio. After launching Visual Studio,
you need to choose the menu option
New->Project.

12/4/2021 C# - SQL CONNECTION 7


12/4/2021 C# - SQL CONNECTION 8
Step 2) The next step is to choose
the project type as a Windows
Forms application. Here, we also
need to mention the name and
location of our project.

12/4/2021 C# - SQL CONNECTION 9


12/4/2021 C# - SQL CONNECTION 10
1. In the project dialog box, we can see various options
for creating different types of projects in Visual Studio.
Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous
step, we will be able to see an option for Windows
Forms Application. Click this option.
3. We then give a name for the application which in our
case is “DemoApplication”. We also need to provide a
location to store our application.
4. Finally, we click the ‘OK’ button to let Visual Studio to
create our project.

12/4/2021 C# - SQL CONNECTION 11


Step 3) Now add a button from the toolbox to the
Windows form. Put the text property of the Button as
Connect. This is how it will look like

12/4/2021 C# - SQL CONNECTION 12


Step 4) Now double click the form so that an event handler is
added to the code for the button click event. In the event
handler, add the below code.

12/4/2021 C# - SQL CONNECTION 13


Code Explanation:-
1. The first step is to create variables, which will be used to create the connection string
and the connection to the SQL Server database.
2. The next step is to create the connection string. The connecting string needs to be
specified correctly for C# to understand the connection string. The connection string
consists of the following parts
1.Data Source – This is the name of the server on which the database resides. In
our case, it resides on a machine called WIN- 50GP30FGO75.
2.The Initial Catalog is used to specify the name of the database
3.The UserID and Password are the credentials required to connect to the
database.
3. Next, we assign the connecting string to the variable cnn. The variable cnn, which is
of type SqlConnection is used to establish the connection to the database.
4. Next, we use the Open method of the cnn variable to open a connection to the
database. We then just display a message to the user that the connection is
established.
5. Once the operation is completed successfully, we then close the connection to the
database. It is always a good practice to close the connection to the database if
nothing else is required to be done on the database.
When the above code is set, and the project is executed using Visual Studio, you will get
the below output. Once the form is displayed,
12/4/2021 click the Connect button.
C# - SQL CONNECTION 14
Output:-

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.

12/4/2021 C# - SQL CONNECTION 16


Step 1) Let’s split the code into 2 parts so that it will be easy to understand for the user.
• The first will be to construct our “select” statement, which will be used to read the data
from the database.
• We will then execute the “select” statement against the database and fetch all the table
rows accordingly.

12/4/2021 C# - SQL CONNECTION 17


Code Explanation:-
1. The first step is to create the following variables
1.SQLCommand – The ‘SQLCommand’ is a class defined within C#. This class is
used to perform operations of reading and writing into the database. Hence, the
first step is to make sure that we create a variable type of this class. This variable
will then be used in subsequent steps of reading data from our database.
2.The DataReader object is used to get all the data specified by the SQL query. We
can then read all the table rows one by one using the data reader.
3.We then define 2 string variables, one is “SQL” to hold our SQL command string.
The next is the “Output” which will contain all the table values.
2. The next step is to define the SQL statement, which will be used against our
database. In our case, it is “Select TutorialID, TutorialName from demotb”. This will
fetch all the rows from the table demotb.
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. Next, we will execute the data reader command, which will fetch all the rows from the
demotb table.
5. Now that we have all the rows of the table with us, we need a mechanism to access
the row one by one. For this, we will use the while statement. The while statement will
be12/4/2021
used to access the rows from the C#data reader one at a time. We then use the
- SQL CONNECTION 18
Step 2) In the final step, we will just display the output to the user and close all the objects
related to the database operation.

12/4/2021 C# - SQL CONNECTION 19


Code Explanation:-
1. We will continue our code by displaying the value of the Output variable using the
MessageBox. The Output variable will contain all the values from the demotb table.
2. We finally close all the objects related to our database operation. Remember this is
always a good practice.

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:-

12/4/2021 C# - SQL CONNECTION 20


C# Insert into Database:-

12/4/2021 C# - SQL CONNECTION 21


Code Explanation:-
1.The first step is to create the following variables
1. SQLCommand – This data type is used to define objects which are used to perform SQL operations against a
database. This object will hold the SQL command which will run against our SQL Server database.
2. The DataAdapter object is used to perform specific SQL operations such as insert, delete and update commands.
3. We then define a string variable, which is “SQL” to hold our SQL command string.

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.

12/4/2021 C# - SQL CONNECTION 22


C# Update database:-

12/4/2021 C# - SQL CONNECTION 23


C# SqlCommand Example With Code
Explanation:-
1. The first step is to create the following variables
1. SQLCommand – This data type is used to define objects which are used to perform SQL operations against a
database. This object will hold the SQL command which will run against our SQL Server database.
2. The dataadapter object is used to perform specific SQL operations such as insert, delete and update
commands.
3. We then define a string variable, which is SQL to hold our SQL command string.
2. The next step is to define the SQL statement which will be used against our database. In our case we are issuing an
update statement, this will update the Tutorial name to “VB.Net Complete” while the TutorialID is unchanged and
kept as 3.
3. Next, we will create the command object, which is used to execute the SQL statement against the database. In the
SQL command, you have passed 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 Update statement against our database.
5. We finally close all the objects related to our database operation. Remember this is always a good practice.

12/4/2021 C# - SQL CONNECTION 24


Deleting Records

12/4/2021 C# - SQL CONNECTION 25


Code Explanation:-

1.The Key difference in this code is that we are


now issuing the delete SQL statement. The delete
statement is used to delete the row in the
demotb table in which the TutorialID has a value
of 3.
2.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 Delete statement against our
database.

12/4/2021 C# - SQL CONNECTION 26


Connecting Controls to data:-
The following screen will show up. Click on the link- “Add Project Data
Source”. When you click on the project data source, you will be
presented with a wizard; this will allow you to define the database
connection.

12/4/2021 C# - SQL CONNECTION 27


12/4/2021 C# - SQL CONNECTION 28
12/4/2021 C# - SQL CONNECTION 29
12/4/2021 C# - SQL CONNECTION 30
12/4/2021 C# - SQL CONNECTION 31
12/4/2021 C# - SQL CONNECTION 32
12/4/2021 C# - SQL CONNECTION 33
12/4/2021 C# - SQL CONNECTION 34

You might also like