【问题标题】:ExecuteNonQuery: Connection property has not been initialized. c sharoExecuteNonQuery:连接属性尚未初始化。 c锋利
【发布时间】:2017-06-27 13:56:50
【问题描述】:

可能是我累了,但任何人都可以说出问题所在?

    SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\deltagare\documents\visual studio 2015\Projects\School\School\school.mdf';Integrated Security=True");
    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'schoolDataSet.student' table. You can move, or remove it, as needed.
        //this.studentTableAdapter.Fill(this.schoolDataSet.student);

        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = "select * from student";

        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        student = new StudentController();
        SqlDataAdapter da = new SqlDataAdapter(cmd);

         da.Fill(dt);

        studentGridView.DataSource = dt;
        conn.Close();
    }

【问题讨论】:

标签: c# sql .net


【解决方案1】:

您必须要么使用SqlCommand(string,SqlConnection) 重载,要么设置SqlCommand.Connection 属性:

SqlCommand cmd = new SqlCommand("select * from student",conn);

或者

cmd.Connection=conn;

【讨论】:

  • 正如我的回答所解释的,您尚未设置 SqlCommandConnection 属性。你有什么不明白的?
【解决方案2】:

您必须在执行命令之前将连接分配给它:

cmd.Connection = conn

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2011-07-22
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多