我打算在网页上实现这样一个功能,就是能够在网页上向数据库添加信息,可是运行的时候报错,代码和错误如下:
  protected void Button1_Click(object sender, EventArgs e)
    {
       
       string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["WdbConnectionString"].ToString();//获取web.config中的数据库连接        string sqlstr = "insert into T_Student(StudentID,Name,Age,ChineseMark,MathMark,EnglishMark) values('";
        sqlstr = sqlstr + TextBox1.Text + "','" + TextBox2.Text +  "','"+ TextBox3.Text + "',' "+ TextBox4.Text +"','"+TextBox5 +"','"+TextBox6 +"')";//构造插入sql语句        using (SqlConnection connection = new SqlConnection(ConnStr))
        {
            SqlCommand command = new SqlCommand(sqlstr, connection);
            connection.Open();//打开数据库连接
            command.ExecuteNonQuery();//执行数据库命令,插入记录
            // Call Close when done reading.
            connection.Close();//关闭数据库
        }        Response.Redirect("search2.aspx");//重定向到default.aspx页面。    }在运行的时候,就在红色字体的部分表错,说T_Student无效,可是这个是我需要插入的表的表名,怎么会无效呢?请各位帮忙看一看。谢谢!!

解决方案 »

  1.   

    LZ跟踪一下string sqlstr这个,看最后的insert字符串是否正确
      

  2.   

    当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'T_Student' 中的标识列插入显式值。
    现在出现的是这个问题了!!不是上面那个了!!但是报错的地方仍然是:command.ExecuteNonQuery();//执行数据库命令,插入记录
    这个地方
      

  3.   

    IDENTITY是自动增长列,你肯定无权限插入啦,既然是自动增长列,你INSERT语句就没必要插入这个字段了
      

  4.   

    将数据类型 varchar 转换为 numeric 时出错。我改了,我想先前可能是学号是标识种子,自动增长所以错误,可是改正过来以后就报错了,是上面的错误,为什么呢?
    改完以后的代码如下:
     protected void Button1_Click(object sender, EventArgs e)
        {
           
           string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["WdbConnectionString"].ToString();//获取web.config中的数据库连接        string sqlstr = "insert into T_Student(Name,Age,ChineseMark,MathMark,EnglishMark) values('";
            sqlstr = sqlstr + TextBox2.Text + "','" + TextBox3.Text +  "','"+ TextBox4.Text + "',' "+ TextBox5.Text +"','"+TextBox6 +"')";//构造插入sql语句        using (SqlConnection connection = new SqlConnection(ConnStr))
            {
                SqlCommand command = new SqlCommand(sqlstr, connection);
                connection.Open();//打开数据库连接
                command.ExecuteNonQuery();//执行数据库命令,插入记录            // Call Close when done reading.
                connection.Close();//关闭数据库
            }        Response.Redirect("search2.aspx");//重定向到default.aspx页面。    }
    谢谢啦!!
      

  5.   

    比如年龄,是数字的,在插入的时候SQL语句前后不要加''  会被理解成字符串的。
      

  6.   

    SqlCommand command = new SqlCommand(sqlstr, connection);在这句加断点 调试触发断点,监视sqlstr看是什么内容,有没有问题,或者copy到sql查询分析器中执行下看能成功么
      

  7.   


    你的意思是说,我这里有问题吗?
    这里:  sqlstr = sqlstr + TextBox2.Text + "','" + TextBox3.Text + "','"+ TextBox4.Text + "',' "+ TextBox5.Text +"','"+TextBox6 +"')"