1 delegate T CreateModelHandel<T>(SqlDataReader reader); 2 class SQLTools 3 { 4 internal static List<T> Query<T>(string sql, CreateModelHandel<T> creator,object args = null) 5 { 6 List<T> list = new List<T>(); 7 using (var conn = new SqlConnection(SQLHelper.ConnStr)) 8 { 9 conn.Open(); 10 11 SqlCommand cmd = new SqlCommand(sql, conn); 12 if (args != null) 13 { 14 foreach (var item in args.GetType().GetProperties()) 15 { 16 string name = item.Name; 17 object value = item.GetValue(args, null); 18 cmd.Parameters.AddWithValue("@"+name, value); 19 } 20 } 21 22 using (var reader = cmd.ExecuteReader()) 23 { 24 while (reader.Read()) 25 { 26 T item = creator(reader); 27 list.Add(item); 28 } 29 } 30 } 31 return list; 32 } 33 34 internal static T QueryFirst<T>(string sql, CreateModelHandel<T> creator, object args = null) 35 { 36 T first = default(T); 37 using (var conn = new SqlConnection(SQLHelper.ConnStr)) 38 { 39 conn.Open(); 40 41 SqlCommand cmd = new SqlCommand(sql, conn); 42 if (args != null) 43 { 44 foreach (var item in args.GetType().GetProperties()) 45 { 46 string name = item.Name; 47 object value = item.GetValue(args, null); 48 cmd.Parameters.AddWithValue("@"+name, value); 49 } 50 } 51 52 using (var reader = cmd.ExecuteReader()) 53 { 54 if (reader.Read()) 55 { 56 first = creator(reader); 57 } 58 } 59 } 60 return first; 61 } 62 63 internal static int NoQuery(string sql, object args = null) 64 { 65 int res = -1; 66 using (var conn = new SqlConnection(SQLHelper.ConnStr)) 67 { 68 conn.Open(); 69 70 SqlCommand cmd = new SqlCommand(sql, conn); 71 if (args != null) 72 { 73 foreach (var item in args.GetType().GetProperties()) 74 { 75 string name = item.Name; 76 object value = item.GetValue(args, null); 77 cmd.Parameters.AddWithValue("@"+name, value); 78 } 79 } 80 81 res = cmd.ExecuteNonQuery(); 82 } 83 return res; 84 } 85 }
调用:
1 public List<RoomType> Get(string typeName) 2 { 3 string sql = "select * from RoomType where TypeName like ‘%‘[email protected]+‘%‘"; 4 return SQLTools.Query<RoomType>(sql, CreateRoom, new { TypeName = typeName }); 5 } 6 7 public int Add(RoomType type) 8 { 9 string sql = "insert RoomType values(@TypeName,@TypePrice)"; 10 return SQLTools.NoQuery(sql, new { TypeName = type.TypeName, TypePrice = type.TypePrice }); 11 } 12 13 public int Change(RoomType type) 14 { 15 string sql = @"update RoomType 16 set TypeName = @TypeName, TypePrice = @TypePrice 17 where TypeID = @TypeID"; 18 return SQLTools.NoQuery(sql, type); 19 } 20 21 public int Remove(int typeID) 22 { 23 string sql = "delete RoomType where TypeID = @TypeID"; 24 return SQLTools.NoQuery(sql, new { TypeID = typeID }); 25 } 26 27 public RoomType CreateRoom(SqlDataReader reader) 28 { 29 RoomType item = new RoomType(); 30 item.TypeID = Convert.ToInt32(reader["TypeID"]); 31 item.TypeName = Convert.ToString(reader["TypeName"]); 32 item.TypePrice = Convert.ToDecimal(reader["TypePrice"]); 33 return item; 34 }
时间: 2024-10-09 03:21:48