C# db 示例代码抛出 "Connection property has not been initialized"

C# db sample code throws "Connection property has not been initialized"

我机器上安装了sqlserver db,visual studio"server explorer"可以连接,连接字符串在"property"中提供,我然后使用此字符串编写我的 C# 代码,如下所示:

SqlConnection conn = new SqlConnection(
    "Data Source=MININT-EP12N1V;Initial Catalog=EmployeeDB;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select FirstName, LastName from Employees");
//above sql can be executed in sql server management studio successfully.
SqlDataReader reader = cmd.ExecuteReader();//throws exception
while (reader.Read())
{
    Console.Write("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
cmd.Dispose();
conn.Close();

抛出异常:

Unhandled Exception: System.InvalidOperationException: ExecuteReader: Connection property has not been initialized.
   at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)

那么如何解决呢?

您没有将 SqlConnection 传递给 SqlCommand,这是必需的,因为除非您提供连接详细信息,否则命令不知道它需要在哪个服务器上执行查询。

尝试:

SqlCommand cmd = new SqlCommand("select FirstName, LastName from Employees",conn);

您总能看到 examples provided in the docs

您可以在文档示例中看到执行方法。您应该在 using 中包装连接,以便在代码块退出后立即将其处理掉:

using(SqlConnection conn = new SqlConnection(
    "Data Source=MININT-EP12N1V;Initial Catalog=EmployeeDB;Integrated Security=True"))
{

    SqlCommand cmd = new SqlCommand("select FirstName, LastName from Employees");
    SqlDataReader reader = cmd.ExecuteReader();
    conn.Open();
    while (reader.Read())
    {
        Console.Write("{1}, {0}", reader.GetString(0), reader.GetString(1));
    }
    reader.Close();
    cmd.Dispose();
}