我可以通过以下方法将数据插入到访问数据库中,该方法可以正常工作,但是如果我尝试插入包含已学到的单引号的文本,则确实会出现问题。
[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(); }
据我了解,解决问题的方法之一是使用参数。老实说,我不确定该怎么做。如何更改上面的代码,以便改为使用参数插入数据?
亲切的问候阿里安
与任何其他查询相同:
a)OleDbCommand用占位符(以前缀)替换其中的实际硬编码参数@, b)将的实例添加OleDbParameter到DbCommand.Parameters属性中。参数名称必须与占位符名称匹配。
OleDbCommand
@
OleDbParameter
DbCommand.Parameters
[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(); } } }