C Sharpとデータベース - CRUDの実行
提供: MochiuWiki : SUSE, EC, PCB
概要
C\#でSQL Serverに対して変更処理(INSERT, UPDATE, DELETE)を実行する方法をまとめる。
1行のみ実行
単一テーブルにしか影響しないようなSQLは1行だけ実行することになる。 このようなクエリを実行する場合、トランザクションを考慮せずそのままExecuteNonQuery()メソッドを実行する方法が簡単である。
using System;
using System.Configuration;
using System.Data.SqlClient;
public void Insert1(string id, string password, string role)
{
// 接続文字列の取得
var connectionString = ConfigurationManager.ConnectionStrings["sqlsvr"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
try
{
// データベースの接続開始
connection.Open();
// SQLの準備
command.CommandText = @"INSERT INTO T_USER (ID, PASSWORD, ROLE_NAME) VALUES (@ID, @PASSWORD, @ROLE_NAME)";
command.Parameters.Add(new SqlParameter("@ID", id));
command.Parameters.Add(new SqlParameter("@PASSWORD", password));
command.Parameters.Add(new SqlParameter("@ROLE_NAME", role));
// SQLの実行
command.ExecuteNonQuery();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
throw;
}
finally
{
// データベースの接続終了
connection.Close();
}
}
}