简体   繁体   中英

C# Execute SqlDataReader missing variable?

I basically copied the example from microsoft.com, but it seems that CommandType does not exist in the current context. The example does not show declaring it.

Thanks

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();

The using the keyword should be used around the connection, command, and datareader. This will ensure that even in the event of an exception occurring, the resources related to those items are released and connections are closed.

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();
}

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

using System.Data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM