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();
}
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
Same as for any other query:
a) Replace actual hardcoded parameters in your
OleDbCommand
with placeholders (prefixed with@
),b) Add instances of
OleDbParameter
to theDbCommand.Parameters
property. Parameter names must match placeholder names.For Microsoft Access the parameters are positional based and not named, you should use
?
as the placeholder symbol although the code would work if you used name parameters provided they are in the same order.See the documentation for OleDbCommand.Parameters Property
Be sure to include the expected schema type where the parameter will be used AND the schema length if applicable.
I also recommend you always use
using
statements around your instances where the type implementsIDisposable
like theOleDbConnection
so that the connection is always closed even if an exception is thrown in the code.Changed Code:
You have to use Parameter to insert Values. Its is allso a security Issue. If you do it like that a sql injection could by made.
Try like this: