在C#2008中从数据库中检索记录

时间:2010-03-03 15:37:58

标签: c# asp.net-3.5

我需要使用以下代码逻辑的语法帮助:

我有一个代码块,可以从数据库中获取电子邮件地址。需要将电子邮件地址分配给带逗号分隔的字符串变量strEmailAddress

我的代码是:

SqlConnection conn = new SqlConnection(strConn);
string sqlEmailAddress = "usp_Get_Email_Address";
SqlCommand cmdEmailAddr = new SqlCommand(sqlEmailAddress, conn);
cmdEmailAddr.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader sqlDREmailAddr = cmdEmailAddr.ExecuteReader();

如何循环记录并将结果存储在以逗号分隔的strEmailAddress中?

4 个答案:

答案 0 :(得分:5)

while (sqlDREmailAddr.Read())
{
    //...process each row here
}

我还会将读者包装在using语句中以确保它已正确关闭:

using (SqlDataReader sqlDREmailAddr = cmdEmailAddr.ExecuteReader())
{
}

根据数据集中列的名称,从每条记录中读取值将如下所示(更新:现在合并所有地址):

var emailAddress = new StringBuilder();
var emailAddressOrdinal = sqlDREmailAddr.GetOrdinal("EmailAddress");
while (sqlDREmailAddr.Read())
{
    if (emailAddress.Length > 0)
        emailAddress.Append(',');
    emailAddress.Append(sqlDREmailAddr.GetString(emailAddressOrdinal));
}

答案 1 :(得分:3)

使用SqlDataReader.Read方法:

while (sqlDREmailAddr.Read())
{
 ...
 // Assumes only one column is returned with the email address
 strEmailAddress = sqlDREmailAddr.GetString(0);
}

答案 2 :(得分:1)

while (sqlDREmailAddr.Read())
  {
    // handle row here
  }

答案 3 :(得分:1)

这就是你要找的......

using (SqlConnection conn = new SqlConnection(strConn)){
   string sqlEmailAddress = "usp_Get_Email_Address";

   using (SqlCommand cmdEmailAddr = new SqlCommand(sqlEmailAddress, conn)){
       cmdEmailAddr.CommandType = CommandType.StoredProcedure;

       conn.Open(); // Typo Glitch!

       using (SqlDataReader sqlDREmailAddr = cmdEmailAddr.ExecuteReader()){

           while(sqlDREmailAddr.Read()){

              if (!sqlDREmailAddr.IsDBNull(sqlDREmailAddr.GetOrdinal("emailAddr"))){

                 // HANDLE THE DB NULL...

              }else{

                 strEmailAddress = sqlDREmailAddr.GetSqlString(sqlDREmailAddr.GetOrdinal("emailAddr"));

                 // Do something with strEmailAddr...

              }
           }
       }
   }

}

注意:

  • conn变量上的拼写错误......
  • 进行检查以确保返回的数据库值不是NULL
  • 调用GetOrdinal以根据emailAddr字符串值返回列,该值对应于SQL Select ... int类型的查询中的列作为GetSqlString ..
  • 的参数

修改:感谢 John Saunders 指出一个blooper!

编辑#2:感谢Peter Lillevold指出错误拼写......

希望这有帮助, 最好的祝福, 汤姆。