【发布时间】:2019-07-12 10:14:15
【问题描述】:
我已经在我的机器上安装了sql server db,Visual Studio“服务器资源管理器”可以连接到它,并且连接字符串在“属性”中提供,然后我使用这个字符串编写我的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)
那么如何解决呢?
【问题讨论】:
-
通过设置SqlCommand的Connection属性?
标签: c# sql-server exception connection