我目前在Vb.Net中有一个DataAccess图层。我对我的ExecuteQuery(作为DataSet)和ExecuteNonQuery函数的实现都不太满意。有没有人有我能看到的代码?我的代码看起来不干净。任何想法或批评也会受到赞赏。
Using odpConn As OracleConnection = New OracleConnection(_myConnString)
odpConn.Open()
If _beginTransaction Then
txn = odpConn.BeginTransaction(IsolationLevel.Serializable)
End If
Try
Using odpCmd As OracleCommand = odpConn.CreateCommand()
odpCmd.CommandType = CommandType.Text
odpCmd.CommandText = sSql
For i = 0 To parameters.Parameters.Count - 1
Dim prm As New OracleParameter
prm = DirectCast(parameters.Parameters(i), ICloneable).Clone
odpCmd.Parameters.Add(prm)
Next
If (odpConn.State = ConnectionState.Closed) Then
odpConn.Open()
End If
iToReturn = odpCmd.ExecuteNonQuery()
If _beginTransaction Then
txn.Commit()
End If
End Using
Catch
txn.Rollback()
End Try
End Using
答案 0 :(得分:0)
一些事情
以下是我正在使用的一些代码。
Public Function QueryDataTable(ByVal storedProcedureName As String, ByVal ParamArray parameters As IDbDataParameter()) As DataTable
Try
Dim command As SqlCommand = CreateCommand(connection, storedProcedureName, parameters)
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter(command)
Dim dtResult As New DataTable()
If transaction Is Nothing Then connection.Open()
adapter.Fill(dtResult)
Return dtResult
Catch ex As Exception
Log.Append("SQL", "QueryDataTable", ex)
Throw
Finally
If transaction Is Nothing Then connection.Close()
End Try
End Function
上面代码中的主要内容
无论如何,上述内容使得无论是否有交易都可以轻松完成。上面的简单交易看起来像这样:
Using sql = new MySqlWrapper(transactionLevel)
dim dt as DataTable = sql.QueryDataTable(a,b)
if EverythingOK(dt) then sql.CommitTransaction()
End Using
当不需要交易时,我可以简单地做
dim dt as DataTable = new MySqlWrapper().sql.QueryDataTable(a,b)