连接到SQL Server在ASP.NET连接到、SQL、Server、ASP

2023-09-04 01:26:02 作者:网易云音乐取什么昵称 网易云昵称独一无二

我想使用asp.net连接至从Visual Web Developer中的SQL Server,而我现在所面临的一些问题。如果有人可以帮助在这方面,我将不胜感激。

I am trying to connect to the SQL Server from Visual Web Developer using asp.net but I am facing some problems If anybody helps in this regard i will be greatful.

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)            
    {     
        SqlConnection conn = new SqlConnection("Server=localhost;" + "Database=DB;User ID=aaaa;" + "Password=aaaa");

        conn.Open(); SqlDataReader reader = conn.ExecuteReader(); 
        while (reader.Read()) {
            employeesLabel.Text += reader["Name"] + "<br />";
        }
        reader.Close(); 
        conn.Close();               
    }
}

我收到错误的说法

I am getting errors saying

System.Data.SqlClient.SqlConnection不包含的ExecuteReader并没有扩展方法的ExecuteReader接受第一种类型System.Data.SqlClient.SqlConnection'的参数定义可以找到(是否缺少using指令或程序集引用?)

'System.Data.SqlClient.SqlConnection' does not contain a definition for 'ExecuteReader' and no extension method 'ExecuteReader' accepting a first argument of type 'System.Data.SqlClient.SqlConnection' could be found (are you missing a using directive or an assembly reference?)

名称为 employeesLabel 并不在当前的背景下存在。

The name 'employeesLabel' does not exist in the current context.

谁能告诉可能的原因是什么?

Can anybody tell the possible reason?

推荐答案

我认为你必须创建SqlCommand类的对象还和命令字符串传递给它的构造。试试这个

i think you have to create object of SqlCommand class also and pass the command string to its constructor. try this"

SqlConnection conn = new SqlConnection("Data Source=serverName;"
           + "Initial Catalog=databaseName;"
           + "Persist Security Info=True;"
           + "User ID=userName;Password=password");

conn.Open();

// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from tableName";
command.CommandType = CommandType.Text;

// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();

// display the results
while (reader.Read()) {
    //whatever you want to do.
}

// close the connection
reader.Close();
conn.Close();