我一直得到#34;连接没有建立"错误。虽然我想,通过打开与sqlLink.Open
和sqlCheck.connection = sqlLink
的连接会发生什么,但这个错误不会出现。
Imports System.Data.OleDb
Public Class StockAdd
Dim path = System.Windows.Forms.Application.StartupPath
Dim sqlLink As OleDbConnection
Private Sub StockAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sqlLink = New OleDbConnection
sqlLink.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\will\Documents\Computing\ComputingProjectDatabase.accdb';")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlCheck As New OleDbCommand
Dim oleRdr As OleDbDataReader
sqlLink.Open()
Try
Using sqlOrder As New OleDbCommand
sqlCheck.Connection = sqlLink
sqlCheck.CommandText = "SELECT count(*) FROM StockSystem WHERE [Stock ID] = @stockID"
sqlCheck.Parameters.AddWithValue("@stockID", TextBox5.Text)
oleRdr = sqlCheck.ExecuteReader()
If oleRdr.HasRows = True Then
oleRdr.Read()
If oleRdr.Item(0) = 0 Then
sqlOrder.CommandText = "INSERT INTO StockSystem ([Stock ID], [Stock Price], [Stock Size], [Stock Quantity], [Stock Category]) VALUES ('" & TextBox5.Text & "','" & TextBox7.Text & "','" & TextBox6.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "')"
sqlOrder.ExecuteNonQuery()
MsgBox("Stock Details Stored.")
Else
MsgBox("Please check you have entered the correct data.")
End If
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
sqlLink.Close()
Me.Close()
Stock.Show()
End Sub
End class
答案 0 :(得分:0)
如果我的眼睛不让我失望,你就不要为sqlOrder命令设置连接。所以它无法执行你的sql文本。
请注意,您不能使用sqlLink连接,因为它由datareader使用。您需要一个新的连接对象(当然具有相同的连接字符串)
作为旁注,您的代码非常容易受到Sql Injection的攻击。如果一个或多个TextBox包含单引号char,则可能会出现严重问题。
始终使用参数化查询作为
之前用于COUNT()语句的查询