[C #] Helper encapsulation series,
1 using System; 2 using System. data; 3 using System. data. SQLite; 4 5 namespace SqliteConsoleApp 6 {7 /// <summary> 8 // SQLite assistant 9 /// </summary> 10 public sealed class SQLiteHelper 11 {12 private const string ConnectionStr = "Data Source = recipes. s3db "; 13 private static SQLiteHelper _ instance; 14 private static readonly object Locker = new object (); 15 16 private SQLiteHelper () 17 {18} 19 2 0 /// <summary> 21 /// obtain instance 22 /// </summary> 23 /// <returns> </returns> 24 public static SQLiteHelper GetInstance () 25 {26 if (_ instance = null) 27 {28 lock (Locker) 29 {30 if (_ instance = null) 31 {32 _ instance = new SQLiteHelper (); 33} 34} 35} 36 37 return _ instance; 38} 39 40 // <summary> 41 // obtain the data table 42 // </summary> 43 // <param name = "plain text"> command to be executed text </param> 44 // <retu Rns> A data table set </returns> 45 public DataTable GetDataTable (string plain text) 46 {47 var dt = new DataTable (); 48 49 try 50 {51 using (var conn = new SQLiteConnection (ConnectionStr) 52 {53 conn. open (); 54 var cmd = new SQLiteCommand (conn) {CommandText = plain text}; 55 using (var reader = cmd. executeReader () 56 {57 dt. load (reader); 58} 59} 60} 61 catch (Exception e) 62 {63 throw new Exception (E. message); 64} 65 66 return dt; 67} 68 69 // <summary> 70 // run the non-query command 71 // </summary> 72 // <param name = "plain text"> to execute command text </param> 73 /// <returns> returns the number of updated rows </returns> 74 public int ExecuteNonQuery (string response text) 75 {76 using (var conn = new SQLiteConnection (ConnectionStr) 77 {78 conn. open (); 79 var cmd = new SQLiteCommand (conn) {CommandText = plain text}; 80 var rowsUpdated = cmd. exec UteNonQuery (); 81 82 return rowsUpdated; 83} 84} 85 86 // <summary> 87 // execute the retrieval single command 88 // </summary> 89 // <param name = "plain text"> command text to be executed </param> 90 // <returns> A string </returns> 91 public string ExecuteScalar (string plain text) 92 {93 using (var conn = new SQLiteConnection (ConnectionStr) 94 {95 conn. open (); 96 var cmd = new SQLiteCommand (conn) {CommandText = plain text}; 97 var value = cm D. ExecuteScalar (); 98 99 if (value! = Null) 100 {101 return value. ToString (); 102} 103} 104 105 return ""; 106} 107} 108}