我在行
上收到错误cmd.ExecuteNonQuery();
说
INSERT INTO语句中的语法错误
我认为我的查询应该有效,我不明白这个问题,而且我已经工作了好几个小时。它按照正确的顺序排列[]
Users
对我不起作用,非常感谢帮助。
<%@ Page Language ="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
protected void Page_Load()
{
String username = Request.Form["username"];
String email = Request.Form["email"];
String password = Request.Form["password1"];
var age = Request.Form["age"];
String country = Request.Form["country"];
String hobbie = Request.Form["skin"];
String sql;
sql = "INSERT INTO Users(UserName, Email, Password, Age, Country, Hobbie) VALUES('" + username + "','" + email + "','" + password + "'," + age + ",'" + country + "','" + skin + "')";
String Path = Server.MapPath("App_Data/Users.accdb");
String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Path;
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
答案 0 :(得分:4)
PASSWORD是MS-Access的保留关键字。用方括号括起来
sql = "INSERT INTO Users(UserName, Email, [Password] ....
但请更改该sql文本以使用参数化查询。此外,如果您能够使用实际值发送此命令,则查询仍然对Sql Injection漏洞开放,并且当您的输入字符串包含单引号时可能会出现解析问题
sql = @"INSERT INTO Users(UserName, Email, [Password], Age, Country, Hobbie)
VALUES(?,?,?,?,?,?)";
....
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("@p1", username);
.... and so on for the other 5 parameters required by the query ....
答案 1 :(得分:2)
我认为密码是一个保留字。使用[密码]
试试这个
sql = "INSERT INTO Users(UserName,Email,[Password],Age,Country,Hobbie) VALUES('" + username + "','" + email + "','" + password + "'," + age + ",'" + country + "','" + skin + "')";
这不推荐。使用参数化查询。如下所示:
sql = "INSERT INTO Users(UserName, Email, [Password], Age, Country, Hobbie)
VALUES(@UserName,@Email,@Password,@Age,@Country,@Hobbie)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserName", username);
cmd.Parameters.AddWithValue("@Email", Email);
cmd.Parameters.AddWithValue("@Password", Password);
cmd.Parameters.AddWithValue("@Age", Age);
cmd.Parameters.AddWithValue("@Country", Country);
cmd.Parameters.AddWithValue("@Hobbie", Hobbie);
答案 2 :(得分:1)
使用[密码]代替密码