sql executenonquery 的查询结果到文本文件vb.net

sql query result from executenonquery to text file vb.net

请看下面代码:

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO


Public Class frm_main

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim sqlFile As String = "ExecOnServer.sql"
        Dim sqlText = File.ReadAllText(sqlFile)
        Dim connStr = "Server=MyServer; Database=MyServer; Integrated Security=SSPI"
        Dim conn = New SqlConnection(connStr)
        Dim str_result_int As Integer
        Dim str_result As String
        Dim sqlCmd = New SqlCommand(sqlText, conn)

        Try
            conn.Open()
            File.AppendAllText("ExecOnServer.txt", vbCrLf & DateTime.Now.ToString("HH:mm dddd, dd MMMM yyyy") & "...Opening Connection..." & vbCrLf)
            str_result_int = sqlCmd.ExecuteNonQuery()
            If str_result_int >= 1 Then
                str_result = "Executed Successfully!!"
            Else
                str_result = "Executed But No Rows were Affected!!"
            End If
            File.AppendAllText("ExecOnServer.txt", DateTime.Now.ToString("HH:mm dddd, dd MMMM yyyy") & "...Executing Query..." & vbCrLf)
            File.AppendAllText("ExecOnServer.txt", DateTime.Now.ToString("HH:mm dddd, dd MMMM yyyy") & " " & str_result & vbCrLf)
        Catch ex As Exception
            'MsgBox("Something went wrong: " & ex.Message)
            File.AppendAllText("ExecOnServer.txt", DateTime.Now.ToString("HH:mm dddd, dd MMMM yyyy") & "...Something went wrong: " & ex.Message & vbCrLf)
        Finally
            If conn.State = ConnectionState.Open Then
                conn.Close()
                File.AppendAllText("ExecOnServer.txt", DateTime.Now.ToString("HH:mm dddd, dd MMMM yyyy") & "...Done!" & vbCrLf)
                'MsgBox("Done")
            End If
            Me.Close()
        End Try
    End Sub
End Class

一切正常!!问题是正在附加的输出文件 (ExecOnServer.txt) 需要包含在 ExecOnServer.sql 中执行的查询的消息。通过消息,我的意思是“(1 行受影响)”或 "Msg 208, Level 16, State 1, Line 3 Invalid object name 'User_Tax_Rates'."。可以使用变量 "str_result" 或创建新变量。

请帮忙。

您有受影响的行数

        If str_result_int >= 1 Then
            str_result = "Executed Successfully!!"
            MessageBox(str_result_int & " row(s) affected")
        Else

以及您可以从 ex.Message 中获取的错误消息 .. 或者放置一个断点并查看 属性 在 ex.

中有什么消息