win7(64bit)、vb2017(community版)、postgresql6.3、npgsqlを使っています。
select文を実行し、データがなければinsert文を実行するというコードを書いています。
vb.net
1 Dim cn As New NpgsqlConnection 2 Dim scmd As New NpgsqlCommand 3 Dim icmd As New NpgsqlCommand 4 Dim dr As NpgsqlDataReader 5 Dim trn As NpgsqlTransaction 6 Dim intCount As Int32 7 Dim strSSQL As String 8 Dim strISQL As String 9 Dim strDateTime As String 10 Try 11 cn.ConnectionString = 接続文字列 12 cn.Open() 13 trn = cn.BeginTransaction() 14 strSSQL = セレクト文 15 scmd.Connection = cn 16 scmd.CommandText = strSSQL 17 dr = scmd.ExecuteReader() 18 If (dr.HasRows = False) Then 19 strISQL = インサート文 20 icmd.CommandText = strISQL 21 intCount = icmd.ExecuteNonQuery 22 trn.Commit() 23 Else 24 trn.Rollback() 25 End If 26 Catch ex As Exception 27 trn.Rollback() 28 strDateTime = Format(Now, "yyyy-MM-dd hh:mm:ss") 29 Call sWriteErrorLog(strDateTime, "DB選択", ex.ToString) 30 Finally 31 cn.Close() 32 dr = Nothing 33 scmd = Nothing 34 icmd = Nothing 35 cn = Nothing 36 End Try
このコードではintCount = icmd.ExecuteNonQueryでエラーになりex.tostringには沢山書かれていますが、先頭に「System.InvalidOperationException: Connection property has not been initialized.」と書かれています。
cnは初期化したつもりはないのですが。。。
それと何故かcatchに行った後trn.Rollback()でエラーになります。
「A command is already in progress」
例外処理でrollbackはできないのでしょうか?
上記2つのことをお聞きしたいです。
ちなみにselect文とinsert文はツールのA5:SQL Mk-2で実行して問題なく実行できます。
よろしくお願いします。
教えていただいた情報を読みコードを書いてみました。
vb.net
1 Using cn As NpgsqlConnection = New NpgsqlConnection() 2 cn.ConnectionString = 接続文字列 3 cn.Open() 4 Dim strSelectSQL As String = セレクト文 5 Dim nSelectCmd As NpgsqlCommand = New NpgsqlCommand(strSelectSQL, cn) 6 Dim dr As NpgsqlDataReader = nSelectCmd.ExecuteReader 7 If (dr.HasRows = False) Then 8 'Dim trn As NpgsqlTransaction = cn.BeginTransaction() 9 Try 10 Dim strInsertSQL As String = インサート文 11 Dim nInsertCmd As NpgsqlCommand = New NpgsqlCommand(strInsertSQL, cn) 12 Dim intCount As Int32 = nInsertCmd.ExecuteNonQuery() 13 'trn.Commit() 14 nInsertCmd.Dispose() 15 Catch ex As Exception 16 'trn.Rollback() 17 Dim strDateTime As String = Format(Now, "yyyy-MM-dd hh:mm:ss") 18 Call sWriteErrorLog(strDateTime, "DB選択", ex.ToString) 19 Finally 20 dr.Dispose() 21 nSelectCmd.Dispose() 22 End Try 23 End If 24 End Using
コメントアウトしていますが、Dim trn As NpgsqlTransaction = cn.BeginTransaction()でエラーになります。
またDim intCount As Int32 = nInsertCmd.ExecuteNonQuery()でcatchに行き以下のようなエラーが出ます。
「"A command is already in progress: セレクトのSQL文"」
vb.netが初心者に近いので解らないのですが。
何が良くないのでしょうか?
なぜトランザクションがエラーになるのでしょうか?

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/16 03:09