手順 3:ADO.NET を使用した SQL への接続を概念実証する

ADO.NET のダウンロード

この C# コードの例は、概念実証としてのみ検討してください。 わかりやすさのためにサンプル コードは簡略化されており、Microsoft が推奨するベスト プラクティスを表しているとは限りません。

1: 接続する

SqlConnection.Open メソッドを使用して、ご自身の SQL データベースに接続します。

using System;
using QC = Microsoft.Data.SqlClient;
  
namespace ProofOfConcept_SQL_CSharp  
{  
	public class Program  
	{  
		static public void Main()  
		{  
			using (var connection = new QC.SqlConnection(  
				"Server=tcp:YOUR_SERVER_NAME_HERE.database.windows.net,1433;" +
				"Database=AdventureWorksLT;User ID=YOUR_LOGIN_NAME_HERE;" +
				"Password=YOUR_PASSWORD_HERE;Encrypt=True;" +
				"TrustServerCertificate=False;Connection Timeout=30;"  
				))  
			{  
				connection.Open();  
				Console.WriteLine("Connected successfully.");  

				Console.WriteLine("Press any key to finish...");  
				Console.ReadKey(true);  
			}  
		}  
	}  
}  
/**** Actual output:  
Connected successfully.  
Press any key to finish...  
****/  

2: クエリを実行する

SqlCommand.ExecuteReader メソッドでは次の処理が実行されます。

  • SQL SELECT ステートメントを SQL システムに発行します。
  • 結果行にアクセスできるように SqlDataReader のインスタンスを返します。
using System;
using DT = System.Data;
using QC = Microsoft.Data.SqlClient;
  
namespace ProofOfConcept_SQL_CSharp  
{  
	public class Program  
	{  
		static public void Main()  
		{  
			using (var connection = new QC.SqlConnection(  
				"Server=tcp:YOUR_SERVER_NAME_HERE.database.windows.net,1433;" +
				"Database=AdventureWorksLT;User ID=YOUR_LOGIN_NAME_HERE;" +
				"Password=YOUR_PASSWORD_HERE;Encrypt=True;" +
				"TrustServerCertificate=False;Connection Timeout=30;"  
				))  
			{  
				connection.Open();  
				Console.WriteLine("Connected successfully.");  
  
				Program.SelectRows(connection);  
  
				Console.WriteLine("Press any key to finish...");  
				Console.ReadKey(true);  
			}  
		}  
  
		static public void SelectRows(QC.SqlConnection connection)  
		{  
			using (var command = new QC.SqlCommand())  
			{  
				command.Connection = connection;  
				command.CommandType = DT.CommandType.Text;  
				command.CommandText = @"  
SELECT  
	TOP 5  
		COUNT(soh.SalesOrderID) AS [OrderCount],  
		c.CustomerID,  
		c.CompanyName  
	FROM  
						SalesLT.Customer         AS c  
		LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh  
			ON c.CustomerID = soh.CustomerID  
	GROUP BY  
		c.CustomerID,  
		c.CompanyName  
	ORDER BY  
		[OrderCount] DESC,  
		c.CompanyName; ";  
  
				QC.SqlDataReader reader = command.ExecuteReader();  
  
				while (reader.Read())  
				{  
					Console.WriteLine("{0}\t{1}\t{2}",  
						reader.GetInt32(0),  
						reader.GetInt32(1),  
						reader.GetString(2));  
				}  
			}  
		}  
	}  
}  
/**** Actual output:  
Connected successfully.  
1       29736   Action Bicycle Specialists  
1       29638   Aerobic Exercise Company  
1       29546   Bulk Discount Store  
1       29741   Central Bicycle Specialists  
1       29612   Channel Outlet  
Press any key to finish...  
****/  

3: 行を挿入する

この例では、次の方法を示します。

  • パラメーターを渡して SQL INSERT ステートメントを安全に実行します。
    • パラメーターを使用して SQL インジェクション攻撃から保護します。
  • 自動生成された値を取得します。
using System;
using DT = System.Data;
using QC = Microsoft.Data.SqlClient;
  
namespace ProofOfConcept_SQL_CSharp  
{  
	public class Program  
	{  
		static public void Main()  
		{  
			using (var connection = new QC.SqlConnection(  
				"Server=tcp:YOUR_SERVER_NAME_HERE.database.windows.net,1433;" +
				"Database=AdventureWorksLT;User ID=YOUR_LOGIN_NAME_HERE;" +
				"Password=YOUR_PASSWORD_HERE;Encrypt=True;" +
				"TrustServerCertificate=False;Connection Timeout=30;"  
				))  
			{  
				connection.Open();  
				Console.WriteLine("Connected successfully.");  
  
				Program.InsertRows(connection);  
  
				Console.WriteLine("Press any key to finish...");  
				Console.ReadKey(true);  
			}  
		}  
  
		static public void InsertRows(QC.SqlConnection connection)  
		{  
			QC.SqlParameter parameter;  
  
			using (var command = new QC.SqlCommand())  
			{  
				command.Connection = connection;  
				command.CommandType = DT.CommandType.Text;  
				command.CommandText = @"  
INSERT INTO SalesLT.Product  
		(Name,  
		ProductNumber,  
		StandardCost,  
		ListPrice,  
		SellStartDate  
		)  
	OUTPUT  
		INSERTED.ProductID  
	VALUES  
		(@Name,  
		@ProductNumber,  
		@StandardCost,  
		@ListPrice,  
		CURRENT_TIMESTAMP  
		); ";  
  
				parameter = new QC.SqlParameter("@Name", DT.SqlDbType.NVarChar, 50);  
				parameter.Value = "SQL Server Express 2014";  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@ProductNumber", DT.SqlDbType.NVarChar, 25);  
				parameter.Value = "SQLEXPRESS2014";  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@StandardCost", DT.SqlDbType.Int);  
				parameter.Value = 11;  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@ListPrice", DT.SqlDbType.Int);  
				parameter.Value = 12;  
				command.Parameters.Add(parameter);  
  
				int productId = (int)command.ExecuteScalar();  
				Console.WriteLine("The generated ProductID = {0}.", productId);  
			}  
		}  
	}  
}  
/**** Actual output:  
Connected successfully.  
The generated ProductID = 1000.  
Press any key to finish...  
****/