我是Vb.net编程的新手,我需要一点帮助,我假装将信息发送到我的数据库,第一个查询给我我需要的ID,并将其声明为" postoid" ,当我后来尝试调用它时(在插入部分中)它表示没有声明,我已经搜索了一百次这个问题,但我找不到答案。
Ps:此代码全部在同一个私人子
中Try
mysqlconn.Open()
queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
READERuser = COMMANDuser1.ExecuteReader
While READERuser.Read
Dim postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
Catch ex As Exception
End Try
Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand
With sqlcommand
.CommandText = sqlquery
.Connection = mysqlconn
.ExecuteNonQuery()
End With
MsgBox("Computador Adicionado")
Dispose()
Close()
答案 0 :(得分:2)
您的变量postoid
在声明的块之外超出范围。
您需要做的就是在Try结构之外声明它:
Dim postoid As String = ""
queryrow = "Select postos_id from postos where postos_nome = @PostosNome"
Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
COMMANDuser1.Parameters.Add("@PostosNome", TextBox1.Text)
mysqlconn.Open()
READERuser = COMMANDuser1.ExecuteReader()
While READERuser.Read
postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
End Using
If postoid <> "" Then
' perform the insert...
我实际上并没有使用Try,因为你的Catch块中没有代码 - Catch块中没有代码可以隐藏错误。你想看到错误。
有关使用SQL参数的信息,请参阅,例如Inserting data into a MySQL table using VB.NET,但请使用.Add
代替.AddWithValue
- 后者并不总是按预期工作。