SQL Server 2019 : C# から利用する2021/05/30 |
C# からの SQL Server 利用例です。
|
|
[1] | Microsoft .NET Core インストール済みを前提として例示します。 |
[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> # 追記 <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> insert into SampleTable ( 4> First_Name, Last_Name) values (N'CentOS', N'Linux'), (N'RedHat', N'Linux'), (N'Fedora', N'Linux' ); 5> 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'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 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 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 |
Sponsored Link |