下面是我用于MySqlTransaction的代码,它运行得很好.... 但问题是因为我使用的是mysql命令的单个实例,我必须在其中使用唯一的PARAMETER。这毁了我的查询。还有其他方法吗....
我尝试在每次查询后处置cmd但没有用.. :(
con.Open()
Dim sqlTran As MySqlTransaction = con.BeginTransaction()
Dim cmd As MySqlCommand = con.CreateCommand()
cmd.Transaction = sqlTran
Dim str As String = Nothing
Try
cmd.CommandText = "SELECT myid FROM memaster where Adate=@adate and ANo=@ano and ASource=@asrc"
cmd.Parameters.AddWithValue("@adate", txt_bpass_adate.Text)
cmd.Parameters.AddWithValue("@ano", txt_bpass_af.Text)
cmd.Parameters.AddWithValue("@asrc", txt_bpass_asource.Text)
str = cmd.ExecuteScalar()
'cmd.Dispose()'
If str Is Nothing Then
cmd.CommandText = "Insert into memaster (ADate,ANo,ASource) values (@aDate,@aNo,@aSRC)"
cmd.Parameters.AddWithValue("@aDate", txt_bpass_adate.Text)
cmd.Parameters.AddWithValue("@aNo", txt_bpass_af.Text)
cmd.Parameters.AddWithValue("@aSRC", txt_bpass_asource.Text)
cmd.ExecuteNonQuery()
End If
sqlTran.Commit()
Catch ex As Exception
Try
sqlTran.Rollback()
Catch ex1 As Exception
End Try
End Try
我实际上想要在单个事务中触发超过4个查询,这样如果出现任何问题我可以回滚它...
如果有人有任何其他方法,请与我分享这个概念......
For index As Integer = 1 To 5
cmd.CommandText = "Insert into detail (ID,BNos,SNo) values (@FID1,@BNo,@SeqN1)"
cmd.Parameters.AddWithValue("@FID1", str)
cmd.Parameters.AddWithValue("@BNo", str1)
cmd.Parameters.AddWithValue("@SeqN1", txt_bpass_sqn1.Text)
cmd.ExecuteNonQuery()
Next
答案 0 :(得分:5)
要在同一事务中执行多个命令,请确保将事务对象分别分配给每个命令:
Dim selectCmd As MySqlCommand = con.CreateCommand()
Dim insertCmd As MySqlCommand = con.CreateCommand()
selectCmd.CommandText = "SELECT ..."
insertCmd.CommandText = "INSERT ..."
Dim sqlTran As MySqlTransaction = con.BeginTransaction()
Try
selectCmd.Transaction = sqlTran
insertCmd.Transaction = sqlTran
...selectCmd.ExecuteScalar()...
...insertCmd.ExecuteNonQuery()...
sqlTran.Commit()
Catch
sqlTran.Rollback()
End Try
正如其他人所提到的那样,Dispose()
对象(IDisposable
)一旦完成它们,通常是个好主意。处理完对象后,将无法再使用它们。
答案 1 :(得分:1)
您可以使用Using关键字来自动配置对象。 我不懂VB但我知道C#。 请将代码转换为VB。
using(MySqlConnection con= new MySqlConnection("connectionString"))
{
con.Open();
using(MysqlTransaction trans=con.BeginTransaction())
{
try
{
//command to executive query
using(MysqlCommand cmd= new MySqlCommand("query", con, trans))
{
cmd.Parameters.AddWithValue("@parameter1", parametervalue1);
cmd.Parameters.AddWithValue("@parameter2", parametervalue2);
cmd.ExecutenonQuery();
cmd.Parameters.Clear();
}
//command to execute query
using(MysqlCommand cmd= new MySqlCommand("query", con, trans))
{
cmd.Parameters.AddWithValue("@parameter1", parametervalue1);
cmd.Parameters.AddWithValue("@parameter2", parametervalue2);
cmd.ExecutenonQuery();
cmd.Parameters.Clear();
}
//command to execute query
using(MysqlCommand cmd= new MySqlCommand("query", con, trans))
{
cmd.Parameters.AddWithValue("@parameter1", parametervalue1);
cmd.Parameters.AddWithValue("@parameter2", parametervalue2);
cmd.ExecutenonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch(Exception ex)
{
trans.Rollback();
}
}
}