尝试在ASP中查询我的数据库时出错

时间:2014-05-22 21:10:09

标签: c# asp.net

我正在尝试让SqlDataReader工作,但是我收到了这个错误:

  

ExecuteReader:尚未初始化Connection属性。

我尝试用SqlDataReader = new SqlDataReader();初始化它 但这又引发了另一个错误。

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=BETSY\\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True";
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM ShoppingList2, con");
        SqlDataReader reader = cmd.ExecuteReader();
        reader.Close();
        con.Close();
    }

2 个答案:

答案 0 :(得分:4)

“SELECT * FROM ShoppingList2,con”

应该是 "SELECT * FROM ShoppingList2", con

答案 1 :(得分:1)

试试这个:

using (SqlConnection con = new SqlConnection("Data Source=BETSY\\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True"))
{
    con.Open();
    using (SqlCommand com = con.CreateCommand())
    {
        // sql setup stuff here
        using (SqlDataReader reader = com.ExecuteReader())
        {
            // read data here
        }
    }
}