目前我正在使用此代码将数据库中的数据读入图表:
Dim Conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile = "\\sch5409.poole.sch.uk\public\HomeDirs\Students\11\11browningale\My Documents\CornmarketCPDDatabase.accdb"
'UserGDCNumber = GDCNumber.Text
Conn.ConnectionString = provider & dataFile
Conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Type Of CPD], [Amount of Hours], [GDC Number] FROM [CPD Table], [Amount of CPD Hours]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Amount of Hours").Points.AddXY(dr("Type Of CPD").ToString, dr("Amount of Hours").ToString)
End While
dr.Close()
cmd.Dispose()
cmd = New OleDbCommand("SELECT [Type of CPD], [Amount of Hours] FROM [CPD Table], [Amount of CPD Hours] WHERE [CPD Table].[CPD ID] = [Amount of CPD Hours].[CPD ID] AND [Amount of CPD Hours].[GDC Number] = GDCNumber.Text", Conn)
dr = cmd.ExecuteReader
问题在于这一行:
cmd = New OleDbCommand("SELECT [Type of CPD], [Amount of Hours] FROM [CPD Table], [Amount of CPD Hours] WHERE [CPD Table].[CPD ID] = [Amount of CPD Hours].[CPD ID] AND [Amount of CPD Hours].[GDC Number] = GDCNumber.Text", Conn)
没有AND [Amount of CPD Hours].[GDC Number] = GDCNumber.Text
我希望我的程序要做的是从文本框GDCNumber.Text
读取数据(我知道我应该首先将它分配给变量),然后在我的查询中使用该数据。
这是错误消息:
System.Data.dll中出现未处理的“System.Data.OleDb.OleDbException”类型异常
附加信息:没有给出一个或多个必需参数的值。“
答案 0 :(得分:2)
您的SQL查询指的是一个名为GDCNumber.Text的东西,但由于这是在VB.Net的结尾,它对SQL Server没有任何意义。相反,你需要像:
cmd = New OleDbCommand("SELECT [Type of CPD], [Amount of Hours] FROM [CPD Table], [Amount of CPD Hours] WHERE [CPD Table].[CPD ID] = [Amount of CPD Hours].[CPD ID] AND [Amount of CPD Hours].[GDC Number] = " & GDCNumber.Text, Conn)
这假设GDCNumber只是一个数字。如果不是那么你想要:
cmd = New OleDbCommand("SELECT [Type of CPD], [Amount of Hours] FROM [CPD Table], [Amount of CPD Hours] WHERE [CPD Table].[CPD ID] = [Amount of CPD Hours].[CPD ID] AND [Amount of CPD Hours].[GDC Number] = '" & GDCNumber.Text & "'", Conn)
这是一个简单的解决方案。但是,像这样构造SQL会让你开启一种叫做SQL注入攻击的东西 - 也就是说有人可能会在该文本框中编写正确的SQL代码并导致代码中出现各种各样的破坏。要解决此问题,您应该了解参数化查询。