通过参数将数据插入到数据库的访问 [英] using parameters inserting data into access database
问题描述
我有下面的方法来将数据插入databasewhich工作正常访问,但我得到一个问题,如果我尝试插入包含单引号我学到的文字。
I have the following method to inserting data into a an access databasewhich works fine but I do get a problem if I try to insert text that contains single quotes I have learned.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = @"INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
据我了解,解决问题的方法之一是使用的参数。我不知道如何做到这一点是诚实的。我怎么能更改上面的code,这样我通过使用参数而不是插入的数据?
From what I understand one of the ways to solve the problem is by using parameters. I am not sure how to do this to be honest. How could I change the above code so that I insert the data by using parameters instead?
亲切的问候
阿里安
Kind regards Arian
推荐答案
同任何其他查询:
a)更换实际艰苦codeD参数=http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.aspx相对=nofollow > 的OleDbCommand
用占位符(prefixed与 @
),结果
b)增加 OleDbParameter <实例/ code>
到的 DbCommand.Parameters
财产。参数名称必须占位符名称相匹配。
a) Replace actual hardcoded parameters in your OleDbCommand
with placeholders (prefixed with @
),
b) Add instances of OleDbParameter
to the DbCommand.Parameters
property. Parameter names must match placeholder names.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
using (OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.Jet.OleDb.4.0;"+
"Data Source="+Server.MapPath("App_Data\\BookRateInitial.mdb"));
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
// create command with placeholders
cmd.CommandText =
"INSERT INTO bookRated "+
"([title], [rating], [review], [frnISBN], [frnUserName]) "+
"VALUES(@title, @rating, @review, @isbn, @username)";
// add named parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("@title", title),
new OleDbParameter("@rating", rating),
...
});
// execute
cmd.ExecuteNonQuery();
}
}
}
这篇关于通过参数将数据插入到数据库的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!