Home >Backend Development >C++ >How to Safely Insert Data with Single Quotes into an Access Database Using Parameters?

How to Safely Insert Data with Single Quotes into an Access Database Using Parameters?

Susan Sarandon
Susan SarandonOriginal
2025-01-22 16:27:11474browse

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:

    The
  • code uses using statements to open and close connections to ensure resources are released correctly.
  • Command text uses placeholders (@title, @rating, etc.) instead of hardcoded values.
  • Use cmd.Parameters.AddRange to create parameters and add them to the command object. Parameter names match placeholders in the command text.
  • The
  • statement of the 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn