Click here to Skip to main content
15,900,615 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Quote:
System.Data.SqlClient.SqlException: 'Invalid column name 'Mugs'.'


I am not sure of the error, as I copied it from a piece of a code on another form that works perfectly.

I am pulling information from a database by using the text off of a button. The button is labeled "Mugs" and the Item Description is also labeled "Mugs". The Column Name is "ItemDescription".

All of the variables are publicly shared from Form1.

Code:

VB
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Form1.lst_Receipt.Items.Count = 0 Then
            Form1.noitemcost = 0
            Form1.noitemtax = 0
            Form1.noitemtotal = 0
            Form1.lst_Receipt.Items.Add("UTA Planetarium")
            Form1.lst_Receipt.Items.Add(FormatDateTime(Today, DateFormat.LongDate))
            Form1.lst_Receipt.Items.Add(FormatDateTime(Today, DateFormat.LongTime))
            Form1.lst_Receipt.Items.Add(" ")
            Form1.lst_Receipt.Items.Add("SubTotal: $" + Form1.noitemcost.ToString)
            Form1.lst_Receipt.Items.Add("Tax: $" + Form1.noitemtax.ToString("F2"))
            Form1.lst_Receipt.Items.Add("Total: $" + Form1.noitemtotal.ToString("F2"))
        End If

        If Form1.reset = 1 Then
            Form1.subtotal = 0
            Form1.tax = 0
            Form1.total = 0
            Form1.tickettax = 0
            Form1.reset = 0
        End If

        Form1.itemdesc = Button1.Text

        Form1.sqlConnection1.Open()

'I believe the next line is where it is hanging up at.
        Form1.cmd = New SqlClient.SqlCommand("SELECT * FROM Inventory WHERE [ItemDescription] =" + Form1.itemdesc, Form1.sqlConnection1)

        Form1.reader = Form1.cmd.ExecuteReader
        Form1.reader.Read()
        Form1.itemcost = Form1.reader(11)
        Form1.proddesc = Form1.reader(3)
        'Form1.itemdesc = Form1.reader(2)
        'itemdesc = reader(2).ToString


        Form1.sqlConnection1.Close()

        Form1.lst_Receipt.Items.RemoveAt(Form1.lst_Receipt.Items.Count - 1)
        Form1.lst_Receipt.Items.RemoveAt(Form1.lst_Receipt.Items.Count - 1)
        Form1.lst_Receipt.Items.RemoveAt(Form1.lst_Receipt.Items.Count - 1)
        Form1.lst_Receipt.Items.Add(Form1.proddesc + vbTab + Form1.quantity + vbTab + Form1.itemcost.ToString("F2"))
        Form1.lst_Receipt.Items.Add("SubTotal: $" + Form1.subtotal.ToString("F2"))
        Form1.lst_Receipt.Items.Add("Tax: $" + Form1.tax.ToString("F2"))
        Form1.lst_Receipt.Items.Add("Total: $" + Form1.total.ToString("F2"))
        Form1.TextBox1.Text = String.Empty
        Form1.TextBox2.Text = ""
        Form1.TextBox1.Focus()
        Close()
    End Sub


This is in a box labeled "Immediate Window":

ClientConnectionId:dfec050c-bd3f-4cef-9e0e-ad871a9487e2
Error Number:207,State:1,Class:16</ExceptionString><DataItems><Data><Key>HelpLink.ProdName</Key><Value>Microsoft SQL Server</Value></Data><Data><Key>HelpLink.ProdVer</Key><Value>13.00.4001</Value></Data><Data><Key>HelpLink.EvtSrc</Key><Value>MSSQLServer</Value></Data><Data><Key>HelpLink.EvtID</Key><Value>207</Value></Data><Data><Key>HelpLink.BaseHelpUrl</Key><Value>http://go.microsoft.com/fwlink</Value></Data><Data><Key>HelpLink.LinkId</Key><Value>20476</Value></Data></DataItems></Exception></TraceRecord>


Hopefully this is enough to go on. This is my first time writing in vb.net and sql.

Please let me know if you have any questions.

What I have tried:

I've checked syntax on both. It works fine when using a barcode to look it up through SQL. The only difference from that code is that it needs to pull from the button1.text for this particular form.
Posted
Updated 6-Aug-18 1:56am
v2

Simple: don't do it like that. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?


There are loads of other things which are badly done here: as Dave mentioned, using Form1 all the time is a bad idea, as is using a common Command object, the magic numbers in your access to the reader data, that you don't check any data is returned at all, ... Basically, wherever you copied that code from, he's an idiot who knows nothing about how to to code properly, and you would be a whole load better of just deleting his "code" and starting again from scratch.

This is a parameterised query done properly:
VB
Using con As New SqlConnection(strConnect)
	con.Open()
	Using cmd As New SqlCommand("SELECT iD, description FROM myTable WHERE ProductName = @PRODNAME", con)
        cmd.Parameters.AddWithValue("@PRODNAME", itemdesc)
		Using reader As SqlDataReader = cmd.ExecuteReader()
			While reader.Read()
				Dim id__1 As Integer = CInt(reader("iD"))
				Dim desc As String = DirectCast(reader("description"), String)
				Console.WriteLine("ID: {0}" & vbLf & "    {1}", iD, desc)
			End While
		End Using
	End Using
End Using
Now use that pattern throughout your app - or lose your DB ...
 
Share this answer
 
v2
Comments
Jennifer Paige Jones 6-Aug-18 19:24pm    
This is my first time using anything like Visual Basic and it is a POS System. I'm usually used to using Matlab for mathematical coding, so most of my code is based off of what I can find on the internet or from stuff in Matlab, so I'm sorry that it is not up to par. I have about 10 different forms and was told that I can have publicly shared values, but I have to call them from the different form. So I'm the idiot that you referred to, but I think for my first time coding in visual basic, on my own with only the help from the internet, I'm doing an okay job. We all gotta start somewhere.

Now to the actual answer, I didn't know that was a thing. I fixed it to how Jochen Arndt, from the solution below, suggested, but once the whole code is up and running, I will look into ways to better my program as a whole. The query only consists of maybe about 30-40 things and my backup is currently an excel file.

This is (not even) version 1, and I'm sure many more versions will be in my future. I'm looking forward to learning more and to using it in my daily life.

Thank you.
First, you don't have to type "Form1" all the time, if this code is part of the Form1 class.

Next, running the code under the debugger will stop the code at the line that threw the exception. The line you highlighted cannot be the one that threw it because it doesn't mention "Mugs" anywhere and you don't appear to have added any parameters to the SqlCommand object.
 
Share this answer
 
Comments
Jennifer Paige Jones 6-Aug-18 19:27pm    
"Mugs" was pulled from a text on a button. I fixed it to where it is working. I have about 10 forms I'm working with, so I've been pulling certain variables from Form1 that I deemed as public. If there is another way, please let me know. This is my first time using visual basic, or any code that is similar.

Thank you.
You have to quote string values in SQL commands:
VB
Form1.cmd = New SqlClient.SqlCommand("SELECT * FROM Inventory WHERE [ItemDescription] ='" + Form1.itemdesc + "'", Form1.sqlConnection1)
Otherwise they are treated as field names or SQL commands.

This would have not happened when using parameterised queries as suggested by OrginalGriff in his solution.

Do it like he suggests instead of fixing your code using the above snippet. The only purpose of this post is to explain what leads to the error message.
 
Share this answer
 
Comments
Jennifer Paige Jones 6-Aug-18 19:27pm    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900