Vb.Net SQL查询语法不正确

时间:2012-01-10 05:32:52

标签: sql-server vb.net

 Command = New OleDbCommand("SELECT dbo.tbl_staff.staff_id, dbo.tbl_staff.username, dbo.tbl_staff.password, dbo.tbl_useraccount.position_id " & _
                                "FROM dbo.tbl_position INNER JOIN " & _
                                "dbo.tbl_useraccount ON dbo.tbl_position.position_id = dbo.tbl_useraccount.position_id INNER JOIN " & _
                                "dbo.tbl_staff ON dbo.tbl_useraccount.useraccount_id = dbo.tbl_staff.staff_id " & _
                                "WHERE (dbo.tbl_staff.username = '" & TextBox1.Text & "') AND (dbo.tbl_staff.password = '" & TextBox2.Text & "')", Connection)

它说错误的语法。

1 个答案:

答案 0 :(得分:3)

如何在VB.NET中运行SQL Server查询

  1. 创建SQL命令 - 您没有设置SQLCommand的连接属性。您可以在不添加代码行的情况下执行此操作。 这是导致错误的原因。

    myCommand = New SqlCommand("Insert Into MyTable values (@value1, @value2)", MyConnection)
    
    • 注意:@ value1,@ value2 - 这些将在稍后发挥作用。这些是SQL参数的占位符。这些将拯救你的屁股。

  2. 插入参数值 - 尽管您没有使用存储过程,但仍需要使用SQL参数。 这不是导致错误的原因

    CMD.Parameters.Add("@value1", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
    CMD.Parameters.Add("@value2", SqlDbType.varchar, 500).Value = TXT_BookName.Text
    
  3. 创建一个执行SQL命令的函数

    ''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD) </summary>'
    ''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."), '
    ''' otherwise if there's just one token, it's a stored procedure command</param>'
    Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
        Dim ds As New DataSet()
    
        Try
            Dim connection As New SqlConnection(connectionString)
            CMD.Connection = connection
    
            'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
            If CMD.CommandText.Contains(" ") Then
                CMD.CommandType = CommandType.Text
            Else
                CMD.CommandType = CommandType.StoredProcedure
            End If
    
            Dim adapter As New SqlDataAdapter(CMD)
            adapter.SelectCommand.CommandTimeout = 300
    
            'fill the dataset'
            adapter.Fill(ds)
            connection.Close()
    
        Catch ex As Exception
            ' The connection failed. Display an error message.'
            Throw New Exception("Database Error: " & ex.Message)
        End Try
    
        Return ds
    End Function