SQL Server 2019 : C# から利用する2020/04/23 |
C# からの SQL Server 利用例です。
|
|
[1] | Microsoft .NET Core インストール済みを前提として例示します。 |
[cent@dlp ~]$ dotnet --version 3.1.103 [cent@dlp ~]$ dotnet new console -o MssqlTest Welcome to .NET Core 3.1! --------------------- SDK Version: 3.1.103 ---------------- Explore documentation: https://aka.ms/dotnet-docs Report issues and find source on GitHub: https://github.com/dotnet/core Find out what's new: https://aka.ms/dotnet-whats-new Learn about the installed HTTPS developer cert: https://aka.ms/aspnet-core-https Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs Write your first app: https://aka.ms/first-net-core-app -------------------------------------------------------------------------------------- Getting ready... The template "Console Application" was created successfully. Processing post-creation actions... Running 'dotnet restore' on MssqlTest/MssqlTest.csproj... Restore completed in 74.3 ms for /home/cent/MssqlTest/MssqlTest.csproj. 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> # 追記 <ItemGroup> <PackageReference Include="System.Data.SqlClient" Version="4.4.0" /> </ItemGroup> </Project> |
[2] | テスト用のデータベース接続用ユーザーとデータベースを作成します。 |
[cent@dlp ~]$ sqlcmd -S localhost -U SA Password: # ログインユーザー作成 1> create login cent with PASSWORD= N'password'; 2> go # [SampleDB] 作成 1> create database SampleDB; 2> go 1> use SampleDB; 2> go Changed database context to 'SampleDB'. # ログインユーザー [cent] と関連付けて DBユーザー作成 1> create user cent for login cent; 2> go # [cent] にDBオーナーロール付与 1> exec sp_addrolemember 'db_owner', 'cent'; 2> go # テストテーブル作成 1> create table SampleTable ( 2> ID int identity(1,1) not null primary key, First_Name NVARCHAR(50), Last_Name NVARCHAR(50) 3> ); 4> insert into SampleTable ( 5> First_Name, Last_Name) values (N'CentOS', N'Linux'), (N'RedHat', N'Linux'), (N'Fedora', N'Linux' 6> ); 7> go |
[3] | 基本的な利用例です。データベースや接続ユーザーは上記で作成したものを使用します。 |
[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(); // SampleTable を Select 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) ); } } } // SampleTable に Insert 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 String userToUpdate = "Redhat"; Console.Write("\r\nUpdating 'Last_Name' for user " + userToUpdate + "\r\n"); sb.Clear(); sb.Append("update SampleTable set Last_Name = N'Maipo' 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 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()); } } } } dotnet restore Restore completed in 4.36 sec for /home/cent/MssqlTest/MssqlTest.csproj.[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 Maipo 3 Fedora Linux 7 Ubuntu Linux Deleting user 'Ubuntu' 1 row(s) deleted |
Sponsored Link |