using parameters inserting data into access database

前端 未结 4 1292
无人及你
无人及你 2020-11-22 11:04

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 lea

4条回答
  •  忘掉有多难
    2020-11-22 11:27

    Same as for any other query:

    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();
          }
       }
    }
    

提交回复
热议问题