2016-01-26 465 views
-3

Image of the error“变量”未声明的错误

我是新来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() 
+1

与您的问题无关,但请仔细阅读使用SQL参数。字符串连接很容易导致SQL注入。 –

+0

您似乎忘记了打开和关闭插入查询的连接,并且您需要在Try..Catch结构外面Dim Dim As As String。顺便说一句,你不应该有一个空的Catch子句,因为这可以防止你看到在Try块中引发的任何错误。 –

+0

似乎问题是这个'pcname'? ,我看不到该变量的声明。 – Japongskie

回答

2

你的变量postoid是外的范围内,可以在声明块外

所有你需要做的就是声明。它外面的尝试结构:

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... 

我没有实际使用尝试在,正如你在Catch块没有代码 - catch块中没有代码有效果隐藏错误。你想看到错误。

有关使用SQL参数的信息,请参阅(例如)Inserting data into a MySQL table using VB.NET,但请使用.Add而不是.AddWithValue - 后者不会按预期工作。

+0

另外'ExecuteScalar'会更好! – shadow

+0

@shadow是的,但有没有结果被返回的凌乱的潜在问题:[执行标量陷阱错误的情况下没有记录返回](http://stackoverflow.com/a/13253718/1115360)。 –

+0

来自MSDN返回值 类型:System.Object 结果集中第一行的第一列,或者如果结果集为空,则为null引用(在Visual Basic中为Nothing)。返回最多2033个字符。“所以我不认为有问题。 – shadow