简体   繁体   English

将查询插入Access C#

[英]Insert query into Access C#

I'm working with Access Data Base, I have a Users Table. 我正在使用Access数据库,有一个用户表。

I have an Insert query : 我有一个插入查询:

DataBase.Execute("Insert into Users(UserID,FirstName,SecondName,UserName,Password,Permission) Values(" +
    obj.PersonID +
    ",'" + obj.FirstName +
    "','" + obj.LastName +
    "','" + username +
    "','" + psw +
    "'," + permission + ")");

I checked all the parameters' values that they are the same with the table's ones... but it says there is a syntax error in my INSERT query. 我检查了所有参数的值,使其与表的值相同...但是它说我的INSERT查询中存在语法错误。

Parameters, parameters, parameters. 参数,参数,参数。 First benefit for your code, you forget about single quotes. 代码的第一个好处是,您无需担心单引号。 Second, you avoid the dreaded SQL injection vulnerability. 其次,您避免了可怕的SQL注入漏洞。 Third, your code will be much easier to read. 第三,您的代码将更容易阅读。 Consider this: 考虑一下:

string insertQuery = "INSERT INTO table (field1, field2, field3) VALUES (@par1, @par2, @par3)";
Database.Execute(insertQuery, var1, var2, var3);

where var1 , var2 and var3 are the variables containing the values you need to insert. 其中var1var2var3是包含您需要插入的值的变量。

There's a simpler (but worse, because it's still vulnerable to SQL injection) solution, that will make your code much more readable than the example you've posted: string.format. 有一个更简单的(但更糟糕的是,因为它仍然容易受到SQL注入的影响)解决方案,这将使您的代码比发布的示例更具可读性:string.format。 Instead of this: 代替这个:

DataBase.Execute("Insert into Users(UserID,FirstName,SecondName,UserName,Password,Permission) Values(" +
obj.PersonID +
",'" + obj.FirstName +
"','" + obj.LastName +
"','" + username +
"','" + psw +
"'," + permission + ")");

you could do something like this, much clearer and much more difficult to forgot some simple quotes: 您可以执行以下操作,更清晰,更难忘记一些简单的引号:

string query = string.Format("Insert into Users (UserID,FirstName,SecondName,UserName,Password,Permission) Values({0}, '{1}', '{2}', '{3}', '{4}', {5})", obj.PersonID, obj.FirstName, obj.LastName, username, psw, permission);
Database.Execute(query);

Consider this as a brief example of the usage of parameters for insertion: http://msdn.microsoft.com/en-us/library/webmatrix.data.database.execute(v=vs.111).aspx 将此视为使用插入参数的简短示例: http : //msdn.microsoft.com/zh-cn/library/webmatrix.data.database.execute(v=vs.111).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM