John Viele said:
Any plans to implement SQL logging in the data adapters? It seems like a
very basic feature. It would help with debugging if one could view the
actual SQL statements that get generated when one does something like:
DataAdapter.Update(SomeDataTable);
Or, is the feature there and I have just overlooked it?
Overlooked it.
See
SqlDataAdapter.RowUpdating
and
SqlDataAdapter.RowUpdated
events.
From the event args you can get to the command and view/edit the parameter
values before they are passed to the database. In the event handler you
could also log the command out.
For instance, here is a RowUpdating event that should be on EVERY
SQLDataAdapter. It's hard to keep the front end from passing empty strings
back in updates sometimes. But I hate empty strings. They are an
abomination. ANSI standard SQL requires SQLServer to store empty strings on
demand, but you should never do it. Here's a handler you can hook up to
your SQLDataAdapter to automatically change empty strings to nulls.
Use it like
dim da as new SQLDataAdapter(cmd)
addhandler da.RowUpdating , addressof ChangeEmptyStringsToNulls
da.update(ds)
Private shared Sub ChangeEmptyStringsToNulls(ByVal sender As Object, ByVal e
As SqlRowUpdatingEventArgs)
Dim p As SqlClient.SqlParameter
For Each p In e.Command.Parameters
If TypeOf p.Value Is String AndAlso DirectCast(p.Value, String) = ""
Then
p.Value = DBNull.Value
End If
Next
End Sub
Here's a handy routine to describe a command, combining the SQL and the
parameter values. Also it works for any provider since it uses the IDB*
interfaces.
Public Shared Function DescribeCommand(ByVal cmd As IDbCommand) As String
Dim msg As New Text.StringBuilder()
msg.Append(cmd.CommandText)
msg.Append(" "c)
Dim p As IDbDataParameter
For Each p In cmd.Parameters
msg.Append(p.ParameterName)
msg.Append("{" & p.DbType.ToString & ") - [")
If TypeOf p.Value Is DBNull Then
msg.Append("(null)")
Else
msg.Append(p.Value.ToString)
End If
msg.Append("]")
Next
Return msg.ToString
End Function
So to log all the SQL statements from a dataadapter:
dim da as new SQLDataAdapter(cmd)
addhandler da.RowUpdated , addressof LogCommands
da.update(ds)
Private shared Sub LogCommands(ByVal sender As Object, ByVal e As
SqlRowUpdatedEventArgs)
System.Diagnostics.Trace.WriteLine(DescribeCommand(e.Command())
End Sub
David