2016-10-26 36 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;