如何处理交易异常

时间:2013-06-19 14:04:06

标签: database exception powershell transactions

我有一个powershell,它从数据库中读取计算机信息行(MS SQL 2008)并将其存储到阅读器中。

# Open the database connection
$conn.Open()

# Create and execute the SQL Query

$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)

$rdr = $cmd.ExecuteReader()

# Read Computer Information into multidimensional array
$count=0
while ($rdr.read()){
    $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), 
    $rdr.GetValue(3))
    $count=$count + 1
}


# Close the database connection
$conn.Close()    

Write-host Finished reading $count IP addresses from database 

大约50%的时间,我得到例外

  

使用“0”参数调用“Read”的异常:“Transaction(Process   ID 107)与另一个进程锁定资源死锁并且已经死锁   被选为死锁受害者。重新运行交易。“在   C:\ script.ps1:83 char:17   + while($ rdr.read<<<<<()){       + CategoryInfo:NotSpecified:(:) [],MethodInvocationException       + FullyQualifiedErrorId:DotNetMethodException

我在数据库中有大约18,000台计算机。抛出此异常时,它只读取10,000,它会不时变化。

如何处理异常以便它读取所有18,000台计算机?

1 个答案:

答案 0 :(得分:1)

尝试将执行包装在try..catch块和这样的循环中:

$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)

do {
  try {
    $rdr = $cmd.ExecuteReader()

    $count=0
    while ($rdr.read()) {
      $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2),
                        $rdr.GetValue(3))
      $count=$count + 1
    }

    $transactionComplete = $true
  } catch {
    $transactionComplete = $false
  }
} until ($transactionComplete)

$conn.Close()

但是,更好的方法是识别并避免死锁情况(如果可能的话)。

相关问题