当我想从数据库中获取数据时,连接未打开

时间:2018-01-07 08:10:22

标签: c# sql-server wpf sqlconnection

当我想在同一窗口中从数据库中获取数据时,连接未打开。例外表示“时间到期”。

代码如下......

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        SqlConnection con = new SqlConnection("Data Source=.; initial catalog=xyz; user id=sa; password=charcha;");
        SqlCommand cmd = new SqlCommand("select * from catagories where Id=1", con);

        con.Open();
        using (con)
        {
            SqlDataReader DR = cmd.ExecuteReader();

            if (DR.Read())
            {

                int Id = Convert.ToInt16(DR["Id"]);
                MainWindow MW = new MainWindow();
                //this.TBlock
                MessageBox.Show(Convert.ToString(DR["Name"]));
                w1TB.Text = Name;
                con.Close();
            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

put" con.Open();"在标签里面#34;使用(con)"

    using (SqlConnection con = new SqlConnection("Data Source=.; initial catalog=xyz; user id=sa; password=charcha;"))
    {
        SqlCommand cmd = new SqlCommand("select * from catagories where Id=1", con);

        con.Open();
        ...etc...
    }