Basic Database Operations Using C#
Last Updated :
31 Jan, 2023
In this article, you are going to learn about how to perform basic database operations using system.data.SqlClient namespace in C#. The basic operations are INSERT, UPDATE, SELECT and DELETE. Although the target database system is SQL Server Database, the same techniques can be applied to other database systems because the query syntax used is standard SQL that is generally supported by all relational database systems.
Prerequisites: Microsoft SQL Server Management Studio
Open Microsoft SQL Server Management Studio and write the below script to create a database and table in it.
create database Demodb;
use Demodb;
CREATE TABLE demo(
articleID varchar(30) NOT NULL PRIMARY KEY,
articleName varchar(30) NOT NULL,
);
insert into demo values(1, 'C#');
insert into demo values(2, 'C++');
After executing the above script following table named demo is created and it contains the following data as shown in the screenshot.

Connecting C# with Database: To work with a database, the first of all you required a connection. The connection to a database normally consists of the below-mentioned parameters.
- Database name or Data Source: The database name to which the connection needs to be set up and connection can be made or you can say only work with one database at a time.
- Credentials: The username and password which needs to be used to establish a connection to the database.
- Optional Parameters: For each database type, you can specify optional parameters to provide more information on how .NET should connect to the database to handle the data.
Note: Here, we are using command prompt to execute these codes. To see the result, you can use the Microsoft SQL Server Management Studio.
Code 1#: Connecting with database in C#
csharp
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class DBConn {
static void Main()
{
Connect();
Console.ReadKey();
}
static void Connect()
{
string constr;
SqlConnection conn;
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300" ;
conn = new SqlConnection(constr);
conn.Open();
Console.WriteLine( "Connection Open!" );
conn.Close();
}
}
}
|
Output:
Connection Open !
Code #2: Using Select Statement and SqlDataReader for accessing the data in C#
csharp
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class SelectStatement{
static void Main()
{
Read();
Console.ReadKey();
}
static void Read()
{
string constr;
SqlConnection conn;
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300" ;
conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd;
SqlDataReader dreader;
string sql, output = "" ;
sql = "Select articleID, articleName from demo" ;
cmd = new SqlCommand(sql, conn);
dreader = cmd.ExecuteReader();
while (dreader.Read()) {
output = output + dreader.GetValue(0) + " - " +
dreader.GetValue(1) + "\n" ;
}
Console.Write(output);
dreader.Close();
cmd.Dispose();
conn.Close();
}
}
}
|
Output:
1 - C#
2 - C++
Code #3: Inserting the data into the database using Insert Statement in C#
csharp
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class InsertStatement {
static void Main()
{
Insert();
Console.ReadKey();
}
static void Insert()
{
string constr;
SqlConnection conn;
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300" ;
conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd;
SqlDataAdapter adap = new SqlDataAdapter();
string sql = "" ;
sql = "insert into demo values(3, 'Python')" ;
cmd = new SqlCommand(sql, conn);
adap.InsertCommand = new SqlCommand(sql, conn);
adap.InsertCommand.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
}
}
}
|
Output:

Code #4: Updating the data into the database using Update Statement in C#
csharp
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class UpdateStatement {
static void Main()
{
Update();
Console.ReadKey();
}
static void Update()
{
string constr;
SqlConnection conn;
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300" ;
conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd;
SqlDataAdapter adap = new SqlDataAdapter();
string sql = "" ;
sql = "update demo set articleName='django' where articleID=3" ;
cmd = new SqlCommand(sql, conn);
adap.InsertCommand = new SqlCommand(sql, conn);
adap.InsertCommand.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
}
}
}
|
Output:

Code #5: Deleting the data into the database using Delete Statement in C#
csharp
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class DeleteStatement {
static void Main()
{
Delete();
Console.ReadKey();
}
static void Delete()
{
string constr;
SqlConnection conn;
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300" ;
conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd;
SqlDataAdapter adap = new SqlDataAdapter();
string sql = "" ;
sql = "delete from demo where articleID=3" ;
cmd = new SqlCommand(sql, conn);
adap.InsertCommand = new SqlCommand(sql, conn);
adap.InsertCommand.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
}
}
}
|
Output:

Similar Reads
Late Binding using Reflection in C#
The two main terms appearing in the above topic are Late Binding and reflection. So let us first define these two terms. The binding of methods and objects during run time is called Late Binding or Dynamic Binding. Reflection is the ability of an assembly to inspect its metadata. Metadata contains t
5 min read
C# | String Operators
The string is an array of characters. The String class represents the text as a series of Unicode characters and it is defined in the .NET base class library. The main use of the String class is to provide the properties, operators and methods so that it becomes easy to work with strings.There are t
4 min read
Basics Operations of File and Directory in C#
In this article, we are going to cover how to create, delete and rename directory and also how to delete and rename the file. Creating a Directory We can create Directory using CreateDirectory() method present in the Directory class. C/C++ Code // C# program to create a directory using System; using
4 min read
File Comparison Using C#
C# is a general-purpose, modern and object-oriented programming language pronounced as âC Sharpâ, in which we can create files. Sometimes we need to do perform operations the on file. This operation can be anything from comparing files byte by byte or needing to check the dates or length of files. F
2 min read
C# String Properties
In C#, a String is an array of characters. The string class represents the text as a series of Unicode characters. It provides various properties and methods so that it becomes easy to work with strings. There are two properties in the string class: Chars[Int32]: Used to get the Char object at a spe
4 min read
Basics of File Handling in C#
Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file.
3 min read
Demonstrating Transactions Using Interface Through C#
The interface is a special class in which we can declare all of our methods. Here in this problem, we are going to create an interface in which we are going to declare all of the required implementations which is necessary for transaction management. Here in this article, we are going to see how rea
2 min read
C# | as Operator Keyword
In software development, typecasting is an inescapable thing. In many cases, developers need to convert an Object(Type) into another Object(Type) and sometimes he/she may get InvalidCastException. So, to overcome such types of exception C# provides the operator keyword as.The as operator is used to
3 min read
C# | Double.ToString() Method | Set - 1
Double.ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation. There are 4 methods in the overload list of this method as follows: ToString(String) Method ToString() Method ToString(IFormatProvider) Method ToString(String, IFormatProvid
3 min read
C# | Double.ToString() Method | Set - 2
Double.ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation. There are 4 methods in the overload list of this method as follows: ToString(String) MethodToString() MethodToString(IFormatProvider) MethodToString(String, IFormatProvider)
2 min read