CentOS Stream 8
Sponsored Link

SQL Server 2019 : Use with C#2021/05/30

 
This is an example to use SQL Server with C#.
[1] This is based on the environment Microsoft .NET Core has been installed.
[cent@dlp ~]$
dotnet --version

5.0.203
[cent@dlp ~]$
dotnet new console -o MssqlTest


Welcome to .NET 5.0!
---------------------
SDK Version: 5.0.203

----------------
Installed an ASP.NET Core HTTPS development certificate.
To trust the certificate run 'dotnet dev-certs https --trust' (Windows and macOS only).
Learn about HTTPS: https://aka.ms/dotnet-https
----------------
Write your first app: https://aka.ms/dotnet-hello-world
Find out what's new: https://aka.ms/dotnet-whats-new
Explore documentation: https://aka.ms/dotnet-docs
Report issues and find source on GitHub: https://github.com/dotnet/core
Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli
--------------------------------------------------------------------------------------
Getting ready...
The template "Console Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on MssqlTest/MssqlTest.csproj...
  Determining projects to restore...
  Restored /home/cent/MssqlTest/MssqlTest.csproj (in 92 ms).
Restore succeeded.

[cent@dlp ~]$
cd MssqlTest

[cent@dlp MssqlTest]$
vi MssqlTest.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
  # add
  <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
  </ItemGroup>
</Project>
[2] Create a sample User and Database for Test.
[cent@dlp ~]$
sqlcmd -S localhost -U SA

Password:
# create login user
1> create login cent with PASSWORD= N'password';
2> go

# create [SampleDB]
1> create database SampleDB;
2> go

1> use SampleDB;
2> go
Changed database context to 'SampleDB'.

# create DB user
1> create user cent for login cent;
2> go

# assign DB owner role to [cent]
1> exec sp_addrolemember 'db_owner', 'cent';
2> go

# create [SampleTable]
1> create table SampleTable (
2> ID int identity(1,1) not null primary key, First_Name NVARCHAR(50), Last_Name NVARCHAR(50) );
3> insert into SampleTable (
4> First_Name, Last_Name) values (N'CentOS', N'Linux'), (N'RedHat', N'Linux'), (N'Fedora', N'Linux' );
5> go
[3] There are some basic usage to connect to SQL Server with C#.
[cent@dlp ~]$
cd MssqlTest

[cent@dlp MssqlTest]$
vi Program.cs
using System;
using System.Text;
using System.Data.SqlClient;

namespace SqlServerSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.DataSource = "127.0.0.1";
                builder.UserID = "cent";
                builder.Password = "password";
                builder.InitialCatalog = "SampleDB";

                Console.Write("Connecting to SQL Server... ");
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                    Console.WriteLine("Done.");
                    StringBuilder sb = new StringBuilder();

                    // Select from SampleTable
                    Console.WriteLine("Reading data from SampleTable...");
                    String sql = "select * from SampleTable;";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine(
                                    "{0} {1} {2}", 
                                    reader.GetInt32(0),
                                    reader.GetString(1),
                                    reader.GetString(2)
                                    );
                            }
                        }
                    }
                    
                    // Insert from SampleTable
                    Console.Write("\r\nInserting into SampleTable...\r\n");
                    sb.Clear();
                    sb.Append("insert SampleTable (First_Name, Last_Name) ");
                    sb.Append("values (@first_name, @last_name);");
                    sql = sb.ToString();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@first_name", "Ubuntu");
                        command.Parameters.AddWithValue("@last_name", "Linux");
                        int rowsAffected = command.ExecuteNonQuery();
                        Console.WriteLine(rowsAffected + " row(s) inserted");
                    }

                    // Update from SampleTable
                    String userToUpdate = "Redhat";
                    Console.Write("\r\nUpdating 'Last_Name' for user " + userToUpdate + "\r\n");
                    sb.Clear();
                    sb.Append("update SampleTable set Last_Name = N'Ootpa' where First_Name = @first_name");
                    sql = sb.ToString();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@first_name", userToUpdate);
                        int rowsAffected = command.ExecuteNonQuery();
                        Console.WriteLine(rowsAffected + " row(s) updated\r\n");
                    }
                    
                    sql = "select * from SampleTable;";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine(
                                    "{0} {1} {2}",
                                    reader.GetInt32(0),
                                    reader.GetString(1),
                                    reader.GetString(2)
                                    );
                            }
                        }
                    }
                    
                    // Delete from SampleTable
                    String userToDelete = "Ubuntu";
                    Console.Write("\r\nDeleting user '" + userToDelete + "'\r\n");
                    sb.Clear();
                    sb.Append("delete from SampleTable where First_Name = @first_name;");
                    sql = sb.ToString();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@first_name", userToDelete);
                        int rowsAffected = command.ExecuteNonQuery();
                        Console.WriteLine(rowsAffected + " row(s) deleted");
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

[cent@dlp MssqlTest]$
dotnet restore

  Determining projects to restore...
  Restored /home/cent/MssqlTest/MssqlTest.csproj (in 4.42 sec).
[cent@dlp MssqlTest]$
dotnet run

Connecting to SQL Server... Done.
Reading data from SampleTable...
1 CentOS Linux
2 RedHat Linux
3 Fedora Linux

Inserting into SampleTable...
1 row(s) inserted

Updating 'Last_Name' for user Redhat
1 row(s) updated

1 CentOS Linux
2 RedHat Ootpa
3 Fedora Linux
4 Ubuntu Linux

Deleting user 'Ubuntu'
1 row(s) deleted
Matched Content