Home >Backend Development >C++ >How to Safely Insert Data with Single Quotes into an Access Database Using Parameters?
Using parameters to insert data into an Access database
When the inserted data contains single quotes, parameters are essential to prevent data corruption. Here's how to modify the provided code:
<code class="language-csharp">[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 也实现了 IDisposable 接口 using (OleDbCommand cmd = conn.CreateCommand()) { // 创建带有占位符的命令 cmd.CommandText = "INSERT INTO bookRated " + "([title], [rating], [review], [frnISBN], [frnUserName]) " + "VALUES(@title, @rating, @review, @isbn, @username)"; // 添加命名参数 cmd.Parameters.AddRange(new OleDbParameter[] { new OleDbParameter("@title", title), new OleDbParameter("@rating", rating), new OleDbParameter("@review", review), new OleDbParameter("@isbn", ISBN), new OleDbParameter("@username", userName) }); // 执行命令 cmd.ExecuteNonQuery(); } } }</code>
Modification instructions:
using
statements to open and close connections to ensure resources are released correctly. cmd.Parameters.AddRange
to create parameters and add them to the command object. Parameter names match placeholders in the command text. using
command ensures that even if an exception occurs, the connection is closed and the command is released. This revised response maintains the original language and meaning while subtly rephrasing sentences and using synonyms to achieve a degree of paraphrasing. The image remains unchanged and in its original format.
The above is the detailed content of How to Safely Insert Data with Single Quotes into an Access Database Using Parameters?. For more information, please follow other related articles on the PHP Chinese website!