【问题标题】:Incorrect syntax near the keyword 'add'关键字“add”附近的语法不正确
【发布时间】:2017-06-13 20:11:36
【问题描述】:

我在学校有一个项目,我需要将我的注册页面与数据库连接起来。 我有这个代码:

if (Request.Form["submit"] != null)
{
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];
    string Passwod = Request.Form["Passwod"];
    string email = Request.Form["email"];
    string add = Request.Form["add"];

    string RegStatus;

    if ((fName == "") || (lName == "") || (Passwod == "") || (email == "") || (add == ""))
    {
        RegStatus = ("missing data or wrong data");
    }
    else
    {
        string selectQuery = "SELECT * FROM " + "[Users]";
        selectQuery += " WHERE ";
        selectQuery += " email = '" + Request.Form["email"] + "'";

        if (MyAdoHelper.IsExist(selectQuery))
        {
            RegStatus = ("email does not exists");
        }
        else
        {
            string insertQuery = "INSERT INTO [Users] (fName,lName,Passwod, email,add) VALUES ('";
            insertQuery += fName + "', '" + lName +"','" + Passwod + "', '" + email + "','" + add +"')";
            Response.Write(insertQuery);
            MyAdoHelper.DoQuery(insertQuery);
            RegStatus = ("Registeration was successful "); 
        }
    }

    Response.Write(RegStatus);
    Response.End();
}

我在填充数据后(运行后)得到的错误是:

System.Data.SqlClient.SqlException:关键字附近的语法不正确 '添加'。

来源错误:

public static void DoQuery(string sql)
    {
        SqlConnection conn = ConnectToDb();
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn); 
        com.ExecuteNonQuery(); //* it says the error is in this line. //*
        com.Dispose();
        conn.Close();
    }

【问题讨论】:

  • 如果您正在学习 SQL,请学习使用参数化查询。不要修改查询字符串。这只会导致语法错误和 SQL 注入漏洞。

标签: c# sql


【解决方案1】:

add 是 SQL 上的关键字。如果你有一个这样命名的字段,你必须使用括号:

INSERT INTO [Users] (fName,lName,Passwod, email,[add]) VALUES... 

另外,如前所述,使用参数而不是字符串连接非常重要:

【讨论】:

    猜你喜欢
    • 2016-06-08
    • 2013-12-16
    • 2017-11-22
    • 2018-06-16
    • 2013-10-29
    • 2014-06-22
    • 1970-01-01
    • 2013-05-04
    • 2013-05-21
    相关资源
    最近更新 更多