· 8 years ago · Jan 21, 2018, 09:48 PM
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using Community.CsharpSqlite.SQLiteClient;
6
7namespace csharp_sqlite_testproject
8{
9 class ThirdStep
10 {
11 // DB接続文å—列
12 // ã“ã®è¨˜è¿°ã§ã‚«ãƒ¬ãƒ³ãƒˆãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã® db.sqlite ãŒæŽ¥ç¶šå…ˆã¨ãªã‚‹
13 private const String connectionStr = @"uri=file:db.sqlite";
14
15 // (å‚考)hogeテーブル作æˆç”¨SQL
16 private const String createTableSQL = @"CREATE TABLE IF NOT EXISTS hoge(name, email)";
17
18 // INSERTæ–‡
19 private const String insertSQL = @"INSERT INTO hoge VALUES (?, ?)";
20
21
22 // prepared statement を使ã£ã¦ã®insert
23 public void Start()
24 {
25 // using使ãˆã‚‹ã¨ã“ã‚ã¯ã©ã‚“ã©ã‚“使ã†
26 using (var con = new SqliteConnection(connectionStr))
27 {
28 con.Open(); // DB接続
29
30 using (var tran = con.BeginTransaction()) // トランザクション開始
31 {
32 using (var cmd = con.CreateCommand()) // SQLオブジェクト作æˆ
33 {
34 cmd.CommandText = insertSQL; // SQLè¨å®š
35
36 foreach (var i in Enumerable.Range(1, 5))
37 {
38 // SqliteParameter ã®ä½œæˆ
39 var param1 = new SqliteParameter()
40 {
41 // ParameterName ã¨ã„ã†ã‚ªãƒ—ションもã‚ã‚‹ã®ãŒã 使ã‚れã¦ãªã„ã£ã½ã„
42 DbType = System.Data.DbType.String,
43 Value = string.Format("user{0}", i),
44 };
45
46 var param2 = new SqliteParameter()
47 {
48 DbType = System.Data.DbType.String,
49 Value = string.Format("user{0}@example.com", i),
50 };
51
52 // コマンドオブジェクトを使ã„ã¾ã‚ã™å ´åˆã¯Clear()ãŒå¿…è¦
53 // addã®é †ç•ªãŒprepared statementã®å‰²ã‚Šå½“ã¦é †ã¨ãªã‚‹
54 cmd.Parameters.Clear();
55 cmd.Parameters.Add(param1);
56 cmd.Parameters.Add(param2);
57
58
59 // 3.7.7.1ã ã¨Prepare()呼ã°ãªãã¦ã‚‚prepared statementãŒé©å¿œã•れる
60 // 今後ã®ä¿®æ£ã§ã©ã†ãªã‚‹ã‹ã‚ã‹ã‚‰ãªã„ã®ã§å‘¼ã¶ã“ã¨ãŒæœ›ã¾ã—ã„ã‹
61 cmd.Prepare();
62
63 cmd.ExecuteNonQuery();
64 }
65
66 }
67
68 tran.Commit(); // コミット
69 }
70 }
71 }
72 }
73}