Variabla在赋值之前使用过。 [英] Variabla used before it has been assigned a value.

查看:55
本文介绍了Variabla在赋值之前使用过。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从你的一个网站上提取了一些这些代码,但在设计时"交易"中强调了这一部分。回滚()" 并且在为其分配值之前使用此错误消息变量
transaction 。任何人都可以帮我解决这个问题。事务回滚()出现在最后一个Msgbox上方

I lifted some of these codes from one of your sites, but this part of it is underlined at design time "transaction. rollback()"  and this error message variable transaction is used before it has been assigned a value. Could anyone help me figure this problem out. transaction rollback() appears just above the last Msgbox

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click Dim conn As New OleDb.OleDbConnection Dim Cmd As New OleDb.OleDbCommand Dim transaction As OleDbTransaction ' open connection conn.ConnectionString = getConnection() Try conn.Open() transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted) Cmd.Connection = conn Cmd.Transaction = transaction 'make a command for the connection and transaction Cmd.CommandText = "INSERT INTO Patients (Title, Surname, FirstName, MiddleName, Phone)Values(?,?,?,?,?)" Cmd.Parameters.AddWithValue("?", cboTitle.Text) Cmd.Parameters.AddWithValue("?", txtSurname.Text) Cmd.Parameters.AddWithValue("?", txtFirstName.Text) Cmd.Parameters.AddWithValue("?", txtMiddleName.Text) ' Cmd.ExecuteNonQuery() 'create paremeters for the second comnamd Cmd.Parameters.Clear() Cmd.CommandText = "INSERT INTO PatientsNOk(Title, Surname.FirstName, MiddleName,Phone)Values(?,?,?,?,?)" Cmd.Parameters.AddWithValue("?", CboTitleNok.Text) Cmd.Parameters.AddWithValue("?", txtSurnameNok.Text) Cmd.Parameters.AddWithValue("?", txtFirstNameNok.Text) Cmd.Parameters.AddWithValue("?", txtMiddleNameNok.Text) Cmd.ExecuteNonQuery() Dim result As Integer = Cmd.ExecuteNonQuery() 'commit transaction transaction.Commit() MsgBox("Both records are written to the db") Catch ex As Exception Console.WriteLine(ex.Message) ' Try to rollback the transaction End Try

transaction.Rollback()
MsgBox("未插入记录")
'这里什么都不做;交易未激活。

'当
'代码退出Using块时,连接自动关闭。
结束子

transaction.Rollback() MsgBox("Record was not inserted") ' Do nothing here; transaction is not active. ' The connection is automatically closed when the ' code exits the Using block. End Sub

推荐答案

Alobi, 

Alobi, 

我认为这是一个警告。但是如果open失败则会成为异常。 

I assume it is a warning. But if the open fails then it becomes an exception. 

我会在你的情况下进行嵌套尝试并将你的回滚放在第一个catch部分而不是它后面。伪代码。

I would make in your case a nested try and put your rollback in the first catch part and not behind it. Pseudo code.

Try
   Open Connection
   Try 
     .....
   Catch 
     Rollback
     Messagebox.show(ex.message)
   End Try
Catch ex as exception
   Messagebox.show(ex.message)
End Try   


这篇关于Variabla在赋值之前使用过。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆