gpt4 book ai didi

c# - SQL 数据读取器读取不一致

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:13 24 4
gpt4 key购买 nike

我在 C# 中有以下代码-

private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();

if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}

我正在从 Windows 窗体上的组合框中获取变量 enqid 的值。组合框的内容是从数据库中检索的。在加载表单时,组合框显示从数据库中检索到的第一个 enquiryID。当我运行我的程序时,数据读取器会跳过循环。但是,如果我在组合框中选择不同的查询,数据读取器会正常工作

最佳答案

您似乎忘记了关联 CommandConnection:

  // SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();

using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this

// have SQL readable
cmd.CommandText =
@"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = @prm_Id";

// use parametrized queries
cmd.Parameters.AddWithValue("@prm_Id", enqid);

using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}

并且从不从不编写类似的代码

  catch (Exception)
{
}

这意味着“忽略所有错误并继续”。

关于c# - SQL 数据读取器读取不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com