2016-10-26 35 views
0

我基本上从microsoft.com复制了该示例,但似乎CommandType在当前上下文中不存在。该示例不显示声明它。C#执行SqlDataReader缺少变量?

由于

string SQLstring = @"Server=DELLXPS\SQLEXPRESS;Database=SEIN;Integrated Security=true"; 
SqlConnection sqlConnection1 = new SqlConnection(SQLstring); 
SqlCommand cmd = new SqlCommand(); 
SqlDataReader reader; 

cmd.CommandText = "SELECT * FROM ResidentUsers"; 
cmd.CommandType = CommandType.Text; 
cmd.Connection = sqlConnection1; 

sqlConnection1.Open(); 

reader = cmd.ExecuteReader(); 
// Data is accessible through the DataReader object here. 

sqlConnection1.Close(); 
+5

你需要为它的命名空间'using'指令。 – SLaks

+0

感谢芽。加工 – birddseedd

回答

1

使用关键字的应围绕连接,命令,和DataReader使用。这将确保即使在发生异常的情况下,与这些项目相关的资源也会被释放并且连接被关闭。

using System.Data.SqlClient; 
using System.Data; 

string SQLstring = @"Server=DELLXPS\SQLEXPRESS;Database=SEIN;IntegratedSecurity=true"; 
string commandText = "SELECT * FROM ResidentUsers"; 
using (var sqlConnection1 = new SqlConnection(SQLstring)) 
using (var cmd = new SqlCommand(commandText, sqlConnection1) { CommandType = CommandType.Text }) 
{ 
    sqlConnection1.Open(); 
    using (var reader = cmd.ExecuteReader()) 
    { 
     // Data is accessible through the DataReader object here. 
    } 
    sqlConnection1.Close(); 
} 
1

你缺少一些命名空间 尝试添加

using System.Data;