发布网友 发布时间:2022-04-07 19:48
共2个回答
懂视网 时间:2022-04-08 00:09
/// <summary> 2 /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) 3 /// </summary> 4 /// <param name="strSQL">查询语句</param> 5 /// <returns>SqlDataReader</returns> 6 public static SqlDataReader ExecuteReader(string strSQL) 7 { 8 SqlConnection connection = new SqlConnection(connectionString); 9 SqlCommand cmd = new SqlCommand(strSQL, connection); 10 try 11 { 12 connection.Open(); 13 SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 14 return myReader; 15 } 16 catch (System.Data.SqlClient.SqlException e) 17 { 18 throw e; 19 } 20 21 }2、三层DAL层方法
1 /// <summary> 2 /// 把读出的数据转换成List 3 /// </summary> 4 public List<int> GetUserList(int hid) 5 { 6 string sql = " select V_UserID from UserVoters where V_HeadlineID=" + hid + ""; 7 SqlDataReader dr = DbHelperSQL.ExecuteReader(sql); 8 List<UserVotersModel> plist = new List<UserVotersModel>(); 9 while (dr.Read()) 10 { 11 UserVotersModel uvm = new UserVotersModel(); 12 uvm.V_UserID = int.Parse(dr["V_UserID"].ToString()); 13 plist.Add(uvm); 14 } 15 List<int> list = new List<int>(); 16 for (int i = 0; i < plist.Count; i++) 17 { 18 list.Add(int.Parse(plist[i].V_UserID.ToString())); 19 } 20 return list; 21 }
3、把List当参数放到sql语句里的方法
1 /// <summary> 2 /// 获得未投票用户列表 3 /// </summary> 4 public DataSet GetNoPersonList(List<int> list) 5 { 6 StringBuilder strSql = new StringBuilder(); 7 if (list != null && list.Count > 0) 8 { 9 string listMes = string.Empty; 10 foreach (int str in list) 11 { 12 listMes += "‘" + str + "‘,"; 13 } 14 strSql.Append("select U_Uid,U_Name,U_Sex,U_Phone,U_QQ from dbo.UsersInfo where U_ID not in(" + listMes.TrimEnd(‘,‘) + ") and U_Level=4 and U_Name=‘‘ ORDER BY U_ID DESC "); 15 return DbHelperSQL.Query(strSql.ToString()); 16 } 17 else 18 { 19 strSql.Append(" select U_Uid,U_Name,U_Sex,U_Phone,U_QQ from dbo.UsersInfo where U_Level=4 and U_Name=‘‘ ORDER BY U_ID DESC "); 20 return DbHelperSQL.Query(strSql.ToString()); 21 } 22 }
二、没有帮助类直接读取数据库
1 /// <summary> 2 /// 读取数据库的信息,并转换成List 3 /// </summary> 4 public List<MailData> GetExpiredLicense() 5 { 6 string connectionString = "Data Source=01;Initial Catalog=Music;Persist Security Info=True;User ID=Musicname;Password=123456"; 7 SqlConnection conn = new SqlConnection(connectionString); 8 conn.Open(); 9 string sql = string.Format( @" select * from Tale" ); 10 11 SqlDataAdapter da = new SqlDataAdapter(sql, connectionString); 12 DataSet ds = new DataSet(); 13 da.Fill(ds); 14 List<MailData> list = new List<MailData>(); //MailData为要查询表的实体类 15 foreach (DataRow item in ds.Tables[0].Rows) 16 { 17 list.Add(MailData.ConvertRow(item)); 18 } 19 return list; 20 }
读取数据库的数据并转换成List<>
标签:
热心网友 时间:2022-04-07 21:17
Class.forName(DB_DRIVER);