Question

I keep getting a "Connection was not established" error. Though I thought, what with opening the Connection with sqlLink.Open and sqlCheck.connection = sqlLink, that this error wouldn't appear.

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
Was it helpful?

Solution

If my eyes don't fail me, you don't set the connection for the sqlOrder command. So it cannot execute your sql text.

Pay attention, you cannot use the sqlLink connection because it is used by the datareader. You need a new connection object (with the same connection string of course)

As a side note, your code is very vulnerable to Sql Injection. And probably could have serious problems if one or more of your TextBoxes contains a single quote char.

Always use a parameterized query as the one used for the COUNT() statement before

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top