1 /// <summary> 2 /// 登录功能 3 /// </summary> 4 /// <param name="model"></param> 5 /// <returns></returns> 6 public UserInfoModel Login(UserInfoModel model) 7 { 8 UserInfoModel userInfoModel = null; 9 string sql = @"select UserName, Password from UserInfos 10 where UserName=@UserName and Password=@Password"; 11 SqlParameter[] paras = 12 { 13 new SqlParameter("@UserName",model.UserName), 14 new SqlParameter("@Password",model.Password) 15 }; 16 DataRow row = DBHelper.GetDataRow(sql, paras); 17 if (row != null) 18 { 19 userInfoModel = new UserInfoModel(); 20 userInfoModel.UserName = row["UserName"].ToString(); 21 userInfoModel.Password = row["Password"].ToString(); 22 } 23 return userInfoModel;//true false 24 }
1 public static DataRow GetDataRow(string sql, params SqlParameter[] paras) 2 { 3 DataTable dt = null; 4 using (SqlConnection conn = new SqlConnection(ConnStr)) 5 { 6 SqlCommand command = new SqlCommand(sql, conn); 7 command.Parameters.AddRange(paras); 8 SqlDataAdapter adapter = new SqlDataAdapter(command); 9 dt = new DataTable(); 10 adapter.Fill(dt); 11 } 12 if (dt.Rows.Count > 0) 13 return dt.Rows[0]; 14 else 15 return null; 16 }
这里为了避免符号为'的sql注入,加了下面的代码
1 string sql = @"select UserName, Password from UserInfos 2 where UserName=@UserName and Password=@Password"; 3 SqlParameter[] paras = 4 { 5 new SqlParameter("@UserName",model.UserName), 6 new SqlParameter("@Password",model.Password) 7 };
让重要的参数变成数组,符号'也就跟着变成了正常的字符串
操作数据库的时候让command.Parameters.AddRange去执行,这时候重要参数就变成了正常的字符串,不会影响我们的sql语句了
1 SqlCommand command = new SqlCommand(sql, conn); 2 command.Parameters.AddRange(paras);