导致您所问问题的主要问题是连接从未打开。
在连接打开之前,您无法执行该命令。
还有一些其他问题:
- 我看不到错误处理,这将帮助您识别错误。可能有一些东西吞噬了你的错误,所以你看不到它们。
- 您正在连接字符串,这使您可以使用SQL Injection。我强烈建议学习参数化查询。
- 您没有使用 using 语句进行连接,这将确保自动关闭和处置
这里列出了几个最佳实践。这是正确使用“使用”语句的摘录。
在 C# 中使用“Using”语句
对于 C# 程序员,确保始终关闭 Connection 和 DataReader 对象的一种便捷方法是使用 using 语句。离开 using 语句的范围时,using 语句会自动对正在“使用”的对象调用 Dispose。例如:
//C#
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}