使用参数将数据插入 Access 数据库
当插入的数据包含单引号时,为了防止数据损坏,参数是必不可少的。以下是如何修改提供的代码:
<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>
修改说明:
using
语句打开和关闭连接,以确保正确释放资源。cmd.Parameters.AddRange
创建参数并将其添加到命令对象中。参数名称与命令文本中的占位符匹配。using
语句确保即使发生异常,连接也会关闭,命令也会被释放。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.
以上是如何使用参数将带单引号的数据安全地插入到 Access 数据库中?的详细内容。更多信息请关注PHP中文网其他相关文章!