objConnection.Open();要放在前面,然后
insertCommand.Connection=objConnection;

解决方案 »

  1.   

    数据库操作问题-_-!
    objConnection.Open();
    SqlCommand insertCommand = new SqlCommand(insertStr, objConnection); 
      

  2.   

    我在 web form中
    ==
    明明是winform
      

  3.   

    我有一个SQL数据库EXAMPLE,里面有一个表  ALL,结构如下 
    id  content  time  status 
    ==
    楼主,你这一个表名和四个字段中all是SQL的运算符(这个最关键),content  time  status 都是sql的关键字..局部变量的名字又和控件的名字相同
    string content = content.Text; 
    string time = time.Text; 修改后的程序如下
    private void button1_Click(object sender, EventArgs e)
    {
        string strConnection = @"server=(local);uid=sa;pwd=sa;database=example";
        SqlConnection objConnection = new SqlConnection(strConnection);
        string insertStr = " INSERT INTO [All] (content,time) VALUES (@content,@time)";
        SqlCommand insertCommand = new SqlCommand(insertStr, objConnection);
        insertCommand.Parameters.AddWithValue("@content", content.Text);
        insertCommand.Parameters.AddWithValue("@time", time.Value.ToString());
        objConnection.Open();
        insertCommand.ExecuteNonQuery();
        objConnection.Close(); 
    }