Syntax Error near "name" - vb.net

conn.Open()
'MsgBox("Established!!!")
cmd.Connection = conn
cmd.CommandText = "SELECT price FROM products WHERE name '" & tb_pname.Text & "'"
dr = cmd.ExecuteReader
While dr.Read
Me.tb_price.Text = Convert.ToString(dr("price"))
End While
conn.Close()

You missed the = equal sign after name
WHERE name = '" & tb_pname.Text & "'"

You are running wrong query. You misses = sign.
Here is correct query
cmd.CommandText = "SELECT price FROM products WHERE name = '" + tb_pname.Text + "'"

If you need the query to not be case-sensitive, you could make a WHERE upper(name) = upper('YourString')
cmd.CommandText = "SELECT price FROM products WHERE upper(name) = upper('" & tb_pname.Text & "')"
You could also use the "like" operator, where you use "WHERE name like 'PutYourTextHere' ", so you can also use wildcards like % for any string.
As an example:
WHERE name like '%Thomson%'
would find any name that contains the string 'Thomson'.
cmd.CommandText = "SELECT price FROM products WHERE name like '" & tb_pname.Text & "'"

Related

how to use multiple combo boxes to filter data

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.
you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.

Incorrect syntax near 's'. Unclosed quotation mark after the character string

I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?

Error in my vb but correct in my sql query

Error in my vb but correct in my sql query. Can somebody can correct my VB code.
This is my wrong code in VB
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & Trim(TextBox11.Text.TrimEnd()) & " OR vendorpnumber ='" & Trim(TextBox2.Text.TrimEnd()) & "'", con)
This is my correct code in mysql query
SELECT *
FROM pcba_info.tblvendorpartnumber
WHERE partnumber = '' or vendorpnumber = '';
You must resolved the problem in SQL injections to
You forgot to include the pair of other single quote.
From
TextBox11.Text.TrimEnd()) & " OR
To
Trim(TextBox11.Text.TrimEnd()) & "' OR
To form as
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & TextBox11.Text.Trim().Replace("'", "''") & "' OR vendorpnumber ='" & TextBox2.Text.Trim().Replace("'", "''") & "'", con)
You need to avoid mixing the VB string functions with those of SQL. Write the entire query inside quotes to be certain will work in SQL.
Try like this
Trim will trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".
Dim S1,S2 as String
S1 = TextBox11.Text
S2 = TextBox12.Text
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & S1.Trim & " OR vendorpnumber ='" & S2.Trim & "'", con)

check the update command, m i doing mistake in its syntax?

his there all,
i'm working on a cms, while trying the update command to update the records, its not working.
here's m complete code for update,
Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone, CheckupDate, Disease, BloodGroup, Doctor, Remarks As String
RegNo = txtRegNo.Text
BedNo = CmbBedNo.SelectedItem.ToString()
BedType = CmbBedType.SelectedItem.ToString()
Charges = txtCharges.Text
PatName = txtPatName.Text
PatAge = txtPatAge.Text
PatAddr = txtPatAdd.Text
Phone = txtPhone.Text
CheckupDate = txtDate.Text
Disease = txtDisease.Text
BloodGroup = cmbBloodGrp.SelectedItem.ToString()
Doctor = cmbDoctor.SelectedItem.ToString()
Remarks = txtRemarks.Text
ID = txtRegNo.Text
Dim conStudent As New OleDbConnection
Dim comStudent As New OleDbCommand
conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
conStudent.Open()
comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ", Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" & Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ", Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" & CheckupDate & "', Disease='" & Disease & "', BloodGroup='" & BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "' WHERE ID=" & RegNo
comStudent.Connection = conStudent
comStudent.CommandType = CommandType.Text
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
conStudent.Close()
one thing, that the fields named with ID, BedNo, BedCharges, Age are set to Number as data type.
First of all, switch to a parameterized query. This will remove any possibilities of Sql Injection, but also avoid the problems with quoting strings, parsing decimal numbers and dates
Dim conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
Dim cmdText = "UPDATE AdmitPt SET ID =?, Bedcategory=?, BedNo=?, BedCharges=?, " & _
"PtName=?, PtAge=?, Address=?, PhoneNo=?, Dates=?, Disease=?, " & _
"BloodGroup=?, Doctor=?, Remarks=? WHERE ID=?"
Using conStudent = new OleDbConnection(conString)
Using comStudent = new OleDbCommand(cmdText, conStudent)
conStudent.Open()
comStudent.Parameters.AddWithValue("#p1", Convert.ToInt32(ID))
comStudent.Parameters.AddWithValue("#p2", BedType)
comStudent.Parameters.AddWithValue("#p3", Convert.ToInt32(BedNo))
comStudent.Parameters.AddWithValue("#p4", Convert.ToDecimal(Charges))
.... and so on for every other question marks in the cmdText ....
.... respecting the exact order of the fields ...................
.... try also to pass the correct datatype for every non string field
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
End Using
End Using

sql query how to put 2 "where"condition

first this is the table relationship.
below is what i'm trying to achieve
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName,record_item.Amount FROM record_item,inventory WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "')", conn)
if i'm trying to get ItemName based on the RecordID that i have,do i need to put 2 condition? if i do, how?
WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "') and WHERE(record_item.ItemID=inventory.ItemID)
WHERE (something) AND (something else)
just do:
SELECT inventory.ItemName,record_item.Amount FROM record_item,inventory
WHERE record_item.RecordID = '" & listbox1.SelectedItem & "' and record_item.ItemID=inventory.ItemID
Without second WHERE clause
WHERE
(record_item.RecordID = '" & listbox1.SelectedItem & "')
and (record_item.ItemID=inventory.ItemID)
instead of using two where condition you can use like this
WHERE (1st condition) AND (2nd condition).
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName,record_item.Amount
FROM record_item,inventory WHERE record_item.RecordID = '" & listbox1.SelectedItem & "' AND record_item.ItemID=inventory.ItemID", conn)
Check below code...
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName, record_item.Amount FROM record_item, inventory WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "' AND record_item.ItemID=inventory.ItemID)", conn)
If your record_item.RecordID is Integer, then below query would work...
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName, record_item.Amount FROM record_item, inventory WHERE (record_item.RecordID = " & listbox1.SelectedItem & " AND record_item.ItemID=inventory.ItemID)", conn)
Can't use more than one WHERE in simple SELECT query, either you can use SUBQUERY or other.
in your case, why you are not implement suggested answer.
also you can use IN clause like,
WHERE (record_item.RecordID IN ('" & listbox1.SelectedItem & "', inventory.ItemID )