C#.NETのサンプルコードを掲載しています。
      
SQLを実行する(SQLServer)
SqlClientデータプロバイダーを使ってSQLServerにSQLを実行するサンプルです。

テストコード
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

private void button_Click(object sender, EventArgs e)
{
    ExecuteNonQuery("UPDATE bread SET name = 'あんぱん(変更)' WHERE id = '0001'");
}

//using System.Data.SqlClient;
/// <summary>
/// SQLを実行します。
/// </summary>
/// <param name="sql">実行するSQL文です</param>
public void ExecuteNonQuery(string sql)
{
    using (SqlCommand command = new SqlCommand())
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = conn.ConnectionString = @"Data Source=PC\SQLEXPRESS1;Initial Catalog=HP;User Id=sa;Password=sa;";

        // トランザクションを開始します。
        conn.Open();
        SqlTransaction transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            command.CommandText = sql;
            command.Connection = conn;
            command.Transaction = transaction;
            command.ExecuteNonQuery();

            //トランザクションをコミットします。
            transaction.Commit();
        }
        catch (System.Exception)
        {
            //トランザクションをロールバックします。
            transaction.Rollback();
            throw;
        }
        finally
        {
            conn.Close();
        }
    }
}

      






Copyright (C) 2011 - 2017 猫の気ままなC#日記