Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

c# - Using parameters inserting data into access database

I have the following method to inserting data into an 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();
}

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...