使用參數將資料插入 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 origmat for paraphrasing. The image remains unchanged and in its origmat.
以上是如何使用參數將帶有單引號的資料安全地插入到 Access 資料庫中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!