gpt4 book ai didi

c# - 执行阅读器 : Connection property has not been initialized

转载 作者:行者123 更新时间:2023-11-30 19:54:53 24 4
gpt4 key购买 nike

我知道这个问题已经被问过很多次了,但是错误是连接让我很难受。

ExecuteReader: Connection property has not been initialized

我正在尝试从表格中搜索电话号码。我几乎尝试了其他线程中给出的所有解决方案,但似乎无法弄清楚如何纠正错误。我必须将命令与 sqlconnection 相关联,但我做不到。

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

using( SqlCommand cmd1 = new SqlCommand() )
{
conn.Open();

cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "SearchName";
SqlParameter p1 = new SqlParameter();
p1.ParameterName = "@Name";//Stored Proc
p1.Value = SearchbyName.Name;
cmd1.Parameters.Add(p1);

using (SqlDataReader dr = cmd1.ExecuteReader())
{
if (dr.Read())
{
while (dr.Read())
{
Console.WriteLine(dr[0] + " " + dr[1]);
}
SearchExit();
}
else
{
Console.WriteLine("No contact found with name {0}", SearchbyName.Name);
}

cmd1.ExecuteNonQuery();
cmd1.Connection = conn;
conn.Close();
SearchExit();
}
}

最佳答案

cmd1.Connection = conn; 

应该在实例化之后立即执行,或者更好的是,在 SqlCommand 构造函数中传递 conn 对象。

关于c# - 执行阅读器 : Connection property has not been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455128/

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