我需要使用以下代码逻辑的语法帮助:
我有一个代码块,可以从数据库中获取电子邮件地址。需要将电子邮件地址分配给带逗号分隔的字符串变量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中?
答案 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
变量上的拼写错误...... GetOrdinal
以根据emailAddr
字符串值返回列,该值对应于SQL Select ... int
类型的查询中的列作为GetSqlString
.. 修改:感谢 John Saunders 指出一个blooper!
编辑#2:感谢Peter Lillevold指出错误拼写......
希望这有帮助, 最好的祝福, 汤姆。