我有自己的DLL(对于数据访问层)。我使用逃脱的字符技术来避免用户输入错误,但是最近我决定通过使用参数化查询来增强我的类,以防止所有可能的错误。修改会变得容易或困难吗?

如何将查询转换为使用参数化查询?

请告诉我一些示例代码以澄清这个想法。

有帮助吗?

解决方案

这就是我在C#.NET和SQL Server中进行操作的方式。

  string sQuery = @"INSERT INTO [UserJob]
                                      (
                                        [SIJCJOBID],
                                        [SIJCCHDID],
                                        [UserID],
                                        [SageDatabaseID],
                                        [MaxLineValue],
                                        [MaxAuthorisationValue],
                                        [UpdatedDate],
                                        [UpdatedUser]
                                      )
                                      VALUES
                                      (
                                        @SIJCJOBID,
                                        @SIJCCHDID,
                                        @UserID,
                                        @SageDatabaseID,
                                        @MaxLineValue,
                                        @MaxAuthorisationValue,
                                        @UpdatedDate,
                                        @UpdatedUser
                                      )
                                      SELECT SCOPE_IDENTITY() AS 'ID'";

                    using (SqlCommand oSqlCommand = new SqlCommand(sQuery))
                    {
                        oSqlCommand.Parameters.AddWithValue("@SIJCJOBID", this.SIJCJOBID);
                        oSqlCommand.Parameters.AddWithValue("@SIJCCHDID", this.SIJCCHDID);
                        oSqlCommand.Parameters.AddWithValue("@UserID", this.UserID);
                        oSqlCommand.Parameters.AddWithValue("@SageDatabaseID", this.SageDatabaseID);
                        oSqlCommand.Parameters.AddWithValue("@MaxLineValue", this.MaxLineValue);
                        oSqlCommand.Parameters.AddWithValue("@MaxAuthorisationValue", this.MaxAuthorisationValue);
                        oSqlCommand.Parameters.AddWithValue("@UpdatedDate", DateTime.Now);
                        oSqlCommand.Parameters.AddWithValue("@UpdatedUser", StaticStore.CurrentUser != null ? StaticStore.CurrentUser.UserName : "SYSTEM");

                        using (DataTable dt = DataTier.ExecuteQuery(oSqlCommand))
                        {
                            if (dt.Rows.Count == 1)
                            {
                                int.TryParse(dt.Rows[0]["ID"].ToString(), out m_UserJobID);
                            }
                        }
                }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top