2012-03-28 68 views
2

您好我一直停留很長一段時間在這個簡單而鈍消息「必須聲明標量變量」VB.net SQL錯誤必須聲明標量變量

我有插入vb.net和SQL代碼數據轉換成簡單的表格。它適用於示例數據,但是當我嘗試使用參數(insertcommand.Parameters.Add(「@ ID」,SqlDbType.Int,3).Value = 50)時,它給我帶來了錯誤。如果我只用一個數字替換@ID就行。

最終.Value = txtid.text如果我可以得到參數的工作。

感謝您的幫助。

 Dim connection As New SqlConnection 
    Dim connectionString As String = 
      "Data Source=LAPTOP-PC\SQLEXPRESS2008;Initial Catalog=golf;" & 
      "Integrated Security=True" 
    connection.ConnectionString = connectionString 
    Dim insertcommand As New SqlCommand 
    insertcommand.Connection = connection 

    insertcommand.Parameters.Add("@ID", SqlDbType.Int, 3).Value = 50 
    'Must declare the scalar variable 

    Dim insertStatement As String = 
    "INSERT INTO Golf (ID, Title, Firstname, Surname, Gender, DOB, Street, Suburb, City, [Available week days], Handicap)" & 
    "Values(@ID, 'Mr', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') " 

    Using insertconnection As New SqlConnection(connectionString) 
     Dim adapter As New SqlDataAdapter() 
     Try 
      insertconnection.Open() 
      adapter.InsertCommand = insertconnection.CreateCommand 
      adapter.InsertCommand.CommandText = insertStatement 
      adapter.InsertCommand.ExecuteNonQuery() 

      MsgBox("Data Inserted !! ") 
     Catch ex As Exception 
      MsgBox(ex.ToString) 
     End Try 

    End Using 

回答

1

的代碼之前聲明的參數是一個位混合起來 - 你建立一個SqlCommand對象,然後不使用它。試試這個:

Using connection As New SqlConnection("Data Source=LAPTOP-PC\SQLEXPRESS2008;Initial Catalog=golf;Integrated Security=True") 
    Dim insertStatement As String = _ 
    "INSERT INTO Golf (ID, Title, Firstname, Surname, Gender, DOB, Street, Suburb, City, [Available week days], Handicap)" _ 
    & "Values(@ID, 'Mr', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') " 
    Using insertcommand As New SqlCommand(insertStatement, connection) 
     connection.Open() 
     insertcommand.Parameters.AddWithValue("@ID", txtid.Text) 
     insertcommand.ExecuteNonQuery() 
    End Using 
End Using 
+0

它的工作!非常感謝! – netchicken 2012-03-28 17:04:28

0

爲什麼不只是寫串入一個變量,使用這個變量插入到你的餐桌?

dim ID as string = txtid.text 

如果你想將數據寫入到一個表,你必須把它包起來這樣'data',就像你與「鴨子」,例如做了。這意味着你的命令字符串必須是這樣的:

"Values('" & ID & "', 'Mr', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') " 
0

你需要使用這樣

SqlParameter @ID = new SqlParameter();