【发布时间】:2021-06-09 20:49:03
【问题描述】:
我有一个 Windows 服务 (VB.NET) 可以将数据从 SQL 表复制到另一个 SQL 表(在不同的数据库和服务器中)。当我启动服务时,它只会给我这个错误:
将数据类型 varchar 转换为数值时出错。
PS:我对这个错误感到惊讶,因为我在源表中没有看到任何 varchar 数据类型。
Source Table(NOR_LABOR) columns and data types 样本源表:http://www.sqlfiddle.com/#!18/bd4fb/1
Destination Table(ALL_LABOR_DETAILS) columns and data types 示例目标表:http://www.sqlfiddle.com/#!18/7eb72/1
Imports System.Configuration
Imports System.Data.SqlClient
Public Class DataCollector
Dim con1, con2 As New SqlConnection
Dim timer1 As Timers.Timer
Dim p_oConn As New Wisys.AllSystem.ConnectionInfo
Protected Overrides Sub OnStart(ByVal args() As String)
con1 = New SqlConnection("Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true")
Try
con1.Open()
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
con2 = New SqlConnection("Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true")
Try
con2.Open()
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
timer1 = New Timers.Timer()
timer1.Interval = 5000
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
con1.Close()
con2.Close()
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
Dim cmd1, cmd2, cmd3 As SqlCommand
'Connecting the Normac Data table
Dim da1 As SqlDataAdapter = New SqlDataAdapter("select ID, RTRIM(trx_date), RTRIM(work_order), RTRIM(department), RTRIM(work_center), RTRIM(operation_no), RTRIM(operator), RTRIM(total_labor_hours), RTRIM(feet_produced), RTRIM(item_no), RTRIM(posted), RTRIM(lot_no), RTRIM(default_bin) from NOR_LABOR where ID > 46006 order by ID", con1)
Dim cb1 As SqlCommandBuilder = New SqlCommandBuilder(da1)
Dim dt1 As DataTable = New DataTable()
da1.Fill(dt1)
Dim i As Integer
'Inserting Normac Data into ALL_LABOR_DETAILS table
For Each dr As DataRow In dt1.Rows
Try
cmd1 = New SqlCommand("Insert into ALL_LABOR_DETAILS values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','','','','','" & dr(11) & "','" & dr(12) & "','','','','','','','')", con2)
i = cmd1.ExecuteNonQuery()
FileIO.WriteLog("Most Recent Normac ID " & mostRecentNormacID)
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
Next
da1.Update(dt1)
cmd1.Dispose()
dt1.Dispose()
da1.Dispose()
End Sub
End Class
【问题讨论】:
-
请从这篇文章中删除 VB6 标签,因为它显然不适用于此代码。
-
一堆问题。第一个问题。确切地知道异常发生的位置将非常有帮助。我建议至少将其作为控制台应用程序进行开发,这比将调试器附加到服务要容易得多。
-
很抱歉先生没有注意到这一点,这只是一个包含 VB6 的大项目,而这只是其中的一部分。刚刚删除了 VB6 标签。
-
下一个问题,为什么所有的字符串连接。一般如果有sql语法问题,查看生成的sql即可轻松解决。更好的使用参数
-
下一个问题。为什么要在初始查询中修剪所有内容。如果你想要可变长度的字符串。使用 varchar 或 nvarchar
标签: sql-server vb.net