我正在尝试使用单个SQL命令执行两个选择我想要选择相关数据并将其插入另一个数据库的另一个表中,但它不起作用,我是新手,有人可以帮我吗?提前谢谢。
Try
If CreateAccessDatabase("C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdb") = True Then
MsgBox("Database Created")
Else
MsgBox("Database Creation Failed")
End If
Dim Sql As String = "Select strCodSeccao,strAbrevTpDoc,strCodExercicio,intNumero " & _
"From Mov_Venda_Cab where dtmdata between @d1 and @d2; Union" & _
"Select Mov_Venda_Lin.Strcodartigo" & _
"from Mov_Venda_Lin,Mov_Venda_Cab where Mov_Venda_Cab.intnumero=Mov_Venda_Lin.intnumero;"
Dim data1, data2 As DateTime
data1 = DateTime.Parse(txtData1.Text)
data2 = DateTime.Parse(txtData2.Text)
data2 = data2.AddMinutes(0)
data2 = data2.AddHours(0)
data2 = data2.AddSeconds(0)
data1 = data1.AddMinutes(0)
data1 = data1.AddHours(0)
data1 = data1.AddSeconds(0)
Dim x As Integer = 0
Dim temp1, temp2, temp3, temp4, temp5 As String
Using con = New SqlConnection("Data Source=" & txtserv.Text & ";" & "Initial Catalog=" & txtBD.Text & ";" & "User ID=" & txtuser.Text & ";" & "Password=" & txtPass.Text & "")
Using cmd = New SqlCommand(Sql, con)
con.Open()
cmd.Parameters.AddWithValue("@d1", data1)
cmd.Parameters.AddWithValue("@d2", data2)
Using reader = cmd.ExecuteReader()
While reader.Read()
Dim strCodSeccao = reader("strCodSeccao").ToString()
temp1 = reader.Item(x)
temp2 = reader.Item(x + 1)
temp3 = reader.Item(x + 2)
temp4 = reader.Item(x + 3)
temp5 = reader.Item(x + 4)
Dim Con2 As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdb;Persist Security Info=True")
Con2.Open()
Dim Ole2 As String = "Insert into Mov_Venda_Cab values('" & temp1 & "','" & temp2 & "','" & temp3 & "','" & temp4 & "','" & temp5 & "');"
Dim OledbCom2 As New OleDb.OleDbCommand(Ole2, Con2)
Try
OledbCom2.ExecuteNonQuery()
Catch Ex As Exception
MsgBox(Ex)
End Try
Con2.Close()
End While
End Using
End Using
End Using
Catch Ex As Exception
MsgBox(Ex)
End Try
答案 0 :(得分:1)
您的INSERT语句用单引号括起所有值。这仅在相应列是所有文本列(varchar,nvarchar等)时才有效。请改用命令参数:
Dim Ole2 As String = "Insert into Mov_Venda_Cab values(@p1, @p2, @p3, @p4, @p5);"
Dim OledbCom2 As New OleDb.OleDbCommand(Ole2, Con2)
OledbCom2.Parameters.AddWithValue("@p1", temp1)
OledbCom2.Parameters.AddWithValue("@p2", temp2)
OledbCom2.Parameters.AddWithValue("@p3", temp3)
OledbCom2.Parameters.AddWithValue("@p4", temp4)
OledbCom2.Parameters.AddWithValue("@p5", temp5)
这适用于任何列类型。
此外,您的SELECT语句仅列出四列,但您正在访问reader
中的五列。
SELECT strCodSeccao, strAbrevTpDoc, strCodExercicio, intNumero FROM ...
代码中的其他内容也很奇怪。您正在定义两个以后从未使用过的连接。
您要为日期添加零小时,分钟和秒(这不会更改日期)。如果您希望日期的日期部分没有时间部分,请改用Date
属性,它返回DateTime
结构的日期部分:
data1 = DateTime.Parse(txtData1.Text).Date
您使用变量x
作为常量值。
您正在While循环中打开和关闭Con2
。在循环之前打开它并在循环之后关闭它。 (对于其他连接,您可以使用Using
- 语句来执行此操作。)