我尝试在c#.NET中使用3轮胎架构在数据库中插入数据,但收到以下错误。
错误:
Server Error in '/3tweb' Application.
Incorrect syntax near the keyword 'User'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'User'.
Source Error:
Line 25: objconn.Open();
Line 26: SqlCommand objcmd = new SqlCommand(sqlstring, objconn);
Line 27: objcmd.ExecuteNonQuery();
Line 28: }
Line 29: public DataSet LoadCustomerDB()
Source File: C:\ASP project\3tweb\DataLayer\Class1.cs Line: 27
我的DataLayer文件如下所示。
的Class1.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DataLayer
{
public class clsDalLayer
{
SqlConnection objconn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
private DataSet ExecuteSql(string sqlcmd)
{
DataSet ds = new DataSet();
objconn.Open();
SqlCommand objcmd = new SqlCommand(sqlcmd, objconn);
SqlDataAdapter objadp = new SqlDataAdapter(objcmd);
objadp.Fill(ds);
objconn.Close();
return ds;
}
private void InsertUpdateDeleteSQLString(string sqlstring)
{
objconn.Open();
SqlCommand objcmd = new SqlCommand(sqlstring, objconn);
objcmd.ExecuteNonQuery();
}
public DataSet LoadCustomerDB()
{
DataSet ds = new DataSet();
string sql = "SELECT id,Name,Username,Age from Person ";
sql +="order by id DESC ";
ds = ExecuteSql(sql);
return ds;
}
public void AddNewUser(string username, string userpass)
{
DataSet ds = new DataSet();
string sql = "INSERT into User (username,password) VALUES ('" + username + "','" + userpass + "')";
InsertUpdateDeleteSQLString(sql);
}
}
}
这里我的故事是我想从视图中将数据插入到数据库中。AddNewUser
方法是从业务层调用两个值。当sql查询正在执行时我得到这种类型的错误。所以请帮助我解决此错误。
答案 0 :(得分:5)
问题是user
是SQL Server中的保留关键字。你需要逃脱它。
这是错误的陈述:
INSERT into User
你应该像这样逃避:
INSERT into [User]
此外,您应该参数化您的SQL语句,因为您现在可以选择SQL injection!
答案 1 :(得分:2)
尝试将用户设为
INSERT into [User]
而不是
INSERT into User
用户是Sql Server中的 reserved keyword
旁注:您的代码易于SQL Injection,请尝试使用parameterize SQL query。