backup: sqlHelper --cSharp
用在只有一两个表操作也极为简单的小玩具里。
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Text; 6 7 namespace Simple.SqlHelpers 8 { 9 internal class SqlHelper 10 { 11 12 /// <summary> 13 /// 数据库连接字符串 14 /// </summary> 15 internal string ConnectionString { get; set; } 16 17 18 public SqlHelper() 19 { 20 } 21 22 23 internal List<T> Query<T>(string sql, Func<SqlDataReader, T> convert, params SqlParameter[] sqlParams) 24 { 25 List<T> result = new List<T>(); 26 27 using (var conn = new SqlConnection(ConnectionString)) 28 { 29 using (var command = new SqlCommand(sql, conn)) 30 { 31 command.Parameters.AddRange(sqlParams); 32 33 conn.Open(); 34 using (var reader = command.ExecuteReader()) 35 { 36 while (reader.Read()) 37 { 38 result.Add(convert(reader)); 39 } 40 } 41 } 42 } 43 return result; 44 } 45 46 internal void Update(string sql, params SqlParameter[] sqlParams) 47 { 48 using (var conn = new SqlConnection(ConnectionString)) 49 { 50 using (var command = new SqlCommand(sql, conn)) 51 { 52 command.Parameters.AddRange(sqlParams); 53 54 conn.Open(); 55 command.ExecuteNonQuery(); 56 } 57 } 58 } 59 60 internal void ActionUpdate(Action<SqlConnection> action) 61 { 62 using (var conn = new SqlConnection(ConnectionString)) 63 { 64 action(conn); 65 } 66 } 67 68 } // class 69 }
1 using System; 2 using System.Collections.Generic; 3 using System.Data.SqlClient; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace Simple.SqlHelpers 9 { 10 internal class SqlDataReaderUtil 11 { 12 public static string ReadString(SqlDataReader reader, string name, string defaultVal) 13 { 14 int ordinal = reader.GetOrdinal(name); 15 return reader.IsDBNull(ordinal) 16 ? defaultVal 17 : reader.GetValue(ordinal).ToString(); 18 } 19 20 public static int ReadInt(SqlDataReader reader, string name, int defaultVal) 21 { 22 int ordinal = reader.GetOrdinal(name); 23 if (reader.IsDBNull(ordinal)) 24 { 25 return defaultVal; 26 } 27 28 return Convert.ToInt32(reader.GetValue(ordinal)); 29 } 30 31 public static long ReadLong(SqlDataReader reader, string name, long defaultVal) 32 { 33 int ordinal = reader.GetOrdinal(name); 34 if (reader.IsDBNull(ordinal)) 35 { 36 return defaultVal; 37 } 38 39 return Convert.ToInt64(reader.GetValue(ordinal)); 40 } 41 42 public static double ReadDouble(SqlDataReader reader, string name, double defaultVal) 43 { 44 int ordinal = reader.GetOrdinal(name); 45 if (reader.IsDBNull(ordinal)) 46 { 47 return defaultVal; 48 } 49 50 return Convert.ToDouble(reader.GetValue(ordinal)); 51 } 52 53 54 } 55 }
--- THE END ---