错误:关键字 'group' 附近的语法不正确



我是WEB开发的新手。我在尝试将数据插入数据库时出错:请帮帮我,我得到的错误是:

"/musa/lrent"应用程序中的服务器错误。

关键字"group"附近的语法不正确。

描述:在执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误以及错误在代码中的来源的更多信息。

异常详细信息:System.Data.SqlClient.SqlException:关键字"group"附近的语法不正确。

Source Error: 

    Line 41:             con.Open();
    Line 42:             SqlCommand objcmd = new SqlCommand("Insert into group(std1,std2,std3,std4) Values('" + usernames[1] + "','" + usernames[2]  +"','"+ usernames[3] + "','"+ usernames[4] + "')", con);
    Line 43:             objcmd.ExecuteNonQuery();
    Line 44:             con.Close();
    Line 45:             
    Source File: g:musarentaladdgroup.aspx.cs    Line: 43 

我的addgroup.aspx文件是-

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class addgroup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Specialized.NameValueCollection nvc = Request.Form;
        string[] usernames = new string[6];
        usernames[1] = ""; usernames[2] = ""; usernames[3] = ""; usernames[4] = "";

        if (!string.IsNullOrEmpty(nvc["username1"]))
        {
            usernames[1] = nvc["username1"];
        }
        if (!string.IsNullOrEmpty(nvc["username2"]))
        {
            usernames[2] = nvc["username2"];
        }
        if (!string.IsNullOrEmpty(nvc["username3"]))
        {
            usernames[3] = nvc["username3"];
        }
        if (!string.IsNullOrEmpty(nvc["username4"]))
        {
            usernames[4] = nvc["username4"];
        }
        if (!string.IsNullOrEmpty(nvc["username1"]))
        {
            Label1.Text = nvc["username1"];
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
            con.Open();
            SqlCommand objcmd = new SqlCommand("Insert into group (std1,std2,std3,std4) Values ('" + nvc["username1"] + "','" + nvc["username2"] + "','" + nvc["username3"] + "','" + nvc["username4"] + "')", con);
            objcmd.ExecuteNonQuery();
            con.Close();
        }
        else
        {
            Label1.Text = "sorry!";
        }
    }
}

GROUP是一个保留关键字,如果你真的想把它用作表名(在我看来这是一种非常糟糕的做法),那么你需要把它封装在方括号中

SqlCommand objcmd = new SqlCommand("Insert into [group] (std1,std2,std3,std4) Values ...

话虽如此,我还是建议学习如何编写参数化查询,而不是字符串连接。你的代码很弱,使用Sql注入很容易破解。

请参阅SqlCommand.Parameters MSDN文档

中的示例

相关内容

最新更新