【问题标题】:ERROR : Incorrect syntax near the keyword 'group'错误:关键字“组”附近的语法不正确
【发布时间】:2015-03-01 23:22:07
【问题描述】:

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

“/musa/rental”应用程序中的服务器错误。

关键字“组”附近的语法不正确。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

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

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:\musa\rental\addgroup.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!";
        }
    }
}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    GROUP 是一个reserved keyword,如果你真的想将它用作表名(我认为这是一个非常糟糕的做法),那么你需要将它封装在方括号中

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

    也就是说,我想建议学习如何编写参数化查询而不是字符串连接。你的代码很弱,使用Sql Injection很容易破解。

    参见SqlCommand.Parameters MSDN documentation中的示例

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2013-12-16
      • 2011-04-07
      • 2017-11-22
      • 2011-08-30
      相关资源
      最近更新 更多