SQL Server 2022 : Use with C#2023/11/30 |
This is an example to use SQL Server with C#.
|
|
[1] | This is based on the environment Microsoft .NET has been installed. |
[centos@dlp ~]$ dotnet --version 7.0.404 [centos@dlp ~]$ dotnet new console -o MssqlTest The template "Console App" was created successfully. Processing post-creation actions... Restoring /home/centos/MssqlTest/MssqlTest.csproj: Determining projects to restore... Restored /home/centos/MssqlTest/MssqlTest.csproj (in 72 ms). Restore succeeded.[centos@dlp ~]$ cd MssqlTest
[centos@dlp MssqlTest]$
vi MssqlTest.csproj <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> # add <ItemGroup> <PackageReference Include="System.Data.SqlClient" Version="4.4.0" /> </ItemGroup> </Project> |
[2] | This is a basic usage example of SQL Server on C#. |
# sample database for testing [centos@dlp ~]$ sqlcmd -S localhost -U centos -d SampleDB3 -Q 'select * from dbo.SampleTable;' Password: ID First_Name Last_Name ----------- ---------------------- --------------------- 1 CentOS Linux 3 RedHat Plow 4 Windows Microsoft (3 rows affected)[centos@dlp ~]$ cd MssqlTest
[centos@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 = "centos"; builder.Password = "P@ssw0rd01"; builder.InitialCatalog = "SampleDB3"; Console.Write("Connecting to SQL Server... "); using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); Console.WriteLine("Done."); StringBuilder sb = new StringBuilder(); // Select data 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 data into 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", "Debian"); command.Parameters.AddWithValue("@last_name", "Linux"); int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(rowsAffected + " row(s) inserted"); } // Update data in SampleTable String userToUpdate = "CentOS"; Console.Write("\r\nUpdating 'Last_Name' for user " + userToUpdate + "\r\n"); sb.Clear(); sb.Append("update SampleTable set Last_Name = N'Stream' 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 data in SampleTable String userToDelete = "Windows"; 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()); } } } } dotnet restore Determining projects to restore... Restored /home/centos/MssqlTest/MssqlTest.csproj (in 4.51 sec).[centos@dlp MssqlTest]$ dotnet run Connecting to SQL Server... Done. Reading data from SampleTable... 1 CentOS Linux 3 RedHat Plow 4 Windows Microsoft Inserting into SampleTable... 1 row(s) inserted Updating 'Last_Name' for user CentOS 1 row(s) updated 1 CentOS Stream 3 RedHat Plow 4 Windows Microsoft 5 Debian Linux Deleting user 'Windows' 1 row(s) deleted[centos@dlp MssqlTest]$ sqlcmd -S localhost -U centos -d SampleDB3 -Q 'select * from dbo.SampleTable;' Password: ID First_Name Last_Name ----------- ------------------- --------------------- 1 CentOS Stream 3 RedHat Plow 5 Debian Linux (3 rows affected) |
Sponsored Link |