我正在使用SQL服务器构建Windows表单应用程序。我遇到的问题是,当我调用.Fill函数时,我得到一个未处理的异常错误。根据其他信息,它表示INNER
关键字附近存在语法错误。到目前为止,我编写了以下代码:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Sean\Documents\Visual Studio 2013\Projects\Baseball\Baseball\Baseball.mdf';Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sql As String
sql = "SELECT teammates.PlayerName, teammates.Number, teammates.BirthDate, Position.Position, teammates.Salary"
sql += "From teammates INNER JOIN Position ON teammates.PositionID = Position.PositionID"
With da
.SelectCommand = New SqlCommand
.SelectCommand.Connection = cn
.SelectCommand.CommandText = sql
.SelectCommand.CommandType = CommandType.Text
cn.Open()
.Fill(ds, "teammates")
cn.Close()
End With
With grdPlayers
.AutoGenerateColumns = True
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
.DataSource = ds
.DataMember = "teammates"
End With
Call FormatGrid()
cn = Nothing
da = Nothing
End Sub
Private Sub FormatGrid()
Dim rightStyle As New DataGridViewCellStyle
rightStyle.Alignment = DataGridViewContentAlignment.MiddleRight
Dim altStyles As New DataGridViewCellStyle
altStyles.BackColor = Color.WhiteSmoke
grdPlayers.AlternatingRowsDefaultCellStyle = altStyles
Dim curStyle As New DataGridViewCellStyle
curStyle.Format = "c"
curStyle.Alignment = DataGridViewContentAlignment.MiddleRight
With grdPlayers
.Columns(0).HeaderText = "Name"
.Columns(1).HeaderText = "Number"
.Columns(2).HeaderText = "Born"
.Columns(4).HeaderText = "Position"
With .Columns(4)
.HeaderCell.Value = "Salary"
.HeaderCell.Style = rightStyle
.DefaultCellStyle = curStyle
End With
.Columns(0).HeaderText = "Name"
End With
End Sub
End Class
答案 0 :(得分:5)
您需要在上一个选定列和FROM
之间留一个空格。现在,您的查询最终为:
SELECT ..., teammates.SalaryFROM
注意缺少空间。所以只需在下一个字符串的开头添加一个空格:
sql += " From teammates INNER
' ^ notice the space
这将导致:
SELECT ..., teammates.Salary FROM
-- ^^ space
答案 1 :(得分:1)
只需将其设为一个字符串,如下所示:
sql = "SELECT teammates.PlayerName, teammates.Number, teammates.BirthDate, Position.Position, teammates.Salary From teammates INNER JOIN Position ON teammates.PositionID = Position.PositionID"