C#.NETのサンプルコードを掲載しています。
      
SQLを実行する(Access)
Oledbデータプロバイダーを使ってAccess(mdbファイル)のテーブルを操作する
サンプルです。
テストコード
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
44
45
46
47
48
49
50
51
52
53

public void MainProc()
{
    string sql = "INSERT INTO bread (id, name, price) VALUES ('S0007', 'サンドイッチ', 100);";
    string path = @"C:\sample.mdb";

    int ret = ExecuteNonQuery(sql, path);
}
    		    		
//System.Data.OleDb;
/// <summary>
/// 指定したmdbファイルに対してSQLを実行します。
/// </summary>
/// <param name="sql">実行するSQL文です</param>
/// <param name="dataSource">mdbファイルの絶対パス</param>
/// <returns>0:正常終了 1:dataSource未設定 2:SQL文がない -1:システムエラー</returns>
public int ExecuteNonQuery(string sql, string dataSource)
{
    if (dataSource == string.Empty) { return 1; }
    if (sql == string.Empty) { return 2; }

    using (OleDbCommand command = new OleDbCommand())
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSource;

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

        try
        {
            command.Connection = conn;
            command.Transaction = transaction;

            command.CommandText = sql;
            command.ExecuteNonQuery();

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

      




Effective C# 4.0
ビル・ワグナー
¥ 3,780

「ダラダラ癖」から抜け出すための10の法則
メリル・E・ダグラス
¥ 1,575



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