2011-01-19 75 views
1

我有我自己的DLL(用于数据访问层)。我使用转义字符技术来避免用户输入错误,但最近我决定使用参数化查询来增强我的类,以防止出现所有可能的错误。修改是简单还是困难?参数化查询问题

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

请给我看一些示例代码来阐明这个想法。

回答

1

这是我将如何在c#.net和SQL服务器中完成它。

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); 
          } 
         } 
       }