Syntax Error with UPDATE command in SQL - sql

Does anything look wrong with this statement? I can't find anything wrong with it...
UPDATE AccountInfo
SET First Name = 'Test', Last Name = 'Account', Street = 'Street', State = 'State', ZipCode = 55555
WHERE id = 1
I'm writing a VB program, and I'm implementing an edit feature. This is the problem code.
Public Function updateAccountInfo(ByVal cp As CPerson, ByVal fName As String, ByVal lName As String, ByVal address As String, ByVal state As String, ByVal zip As Integer) As Boolean
Dim sql, sql2 As String
sql = "UPDATE AccountInfo SET First Name = '" & fName & "', Last Name = '" & lName & "', Street = '" & address & _
"', State = '" & state & "', ZipCode = " & zip & " WHERE id = " & cp.returnIDOnlyNumber
sql2 = "UPDATE Accounts SET First Name = '" & fName & "', Last Name = '" & lName & "' WHERE id = " & cp.returnIDOnlyNumber
Return do_command(sql, sql2)
End Function
Private Function do_command(ByVal sql As String, ByVal sql2 As String) As Boolean
Dim command As OleDbCommand
Try
conn.Open()
command = New OleDbCommand(sql, conn)
command.ExecuteNonQuery()
conn.Close()
conn.Open()
command = New OleDbCommand(sql2, conn)
command.ExecuteNonQuery()
conn.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function

Yes, you have space in the names. If you really have them, then you need to escape them, perhaps with square braces:
UPDATE AccountInfo
SET [First Name] = 'Test',
[Last Name] = 'Account',
Street = 'Street',
State = 'State',
ZipCode = '55555'
WHERE id = 1;
It is better to have names with no spaces. Also, the zip code should be stored as a string, not a number, otherwise you will lose leading zeros.

Related

Preventing SQL from injection attacks

I have a program that contains SQL queries, and it was pointed out to me yesterday that it was wide open to SQL injection attacks. After doing some research, I could see that to fix this, I needed to use parameters instead.
I have the following code... How do paramterise this?
Public Shared Function SaveNewPerson(ByVal firstName As String, lastName As String, ByVal age As Integer, ByVal postcode As String, m_cn As OleDbConnection)
Dim tr As OleDbTransaction = Nothing
Try
tr = m_cn.BeginTransaction()
Dim Dc As New OleDbCommand
Dc.Connection = m_cn
Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES('" & firstName & "', '" & lastName & "', '" & age & "', '" & postcode & "')"
Dc.Transaction = tr
Dc.ExecuteNonQuery()
Dim personID As Integer
Dc.CommandText = "SELECT SCOPE_IDENTITY() AS personID"
Dc.CommandType = CommandType.Text
personID = CType(Dc.ExecuteScalar(), Integer)
tr.Commit()
Catch ex As Exception
tr.Rollback()
Throw
End Try
End Function
I would make a stored procedure first to insert into the sql server and then use
dc.commandText = "Your stored procedure name"
dc.commandType = CommandType.StoredProcedure
Dim myParam as oledb.OleDbParameter = dc.parameters.add("#personID", oledbtype.int)
myParam.Direction = ParameterDirection.ReturnValue
dc.Parameters.Add("#firstName", OleDbType.VarChar).Value = [firstname]
....
....
Dim returnId as Integer = Cint(dc.Parameters("#personID").Value)
Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES('" & firstName & "', '" & lastName & "', '" & age & "', '" & postcode & "')"
Change this to
Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES(?, ?, ?, ?)"
Dc.Parameters.Add("#first", OleDbType.VarChar, firstName)
Dc.Parameters.Add("#last", OleDbType.VarChar, lastName)
Dc.Parameters.Add("#age", OleDbType.Integer, age)
Dc.Parameters.Add("#postcode", OleDbType.VarChar, postcode )
(Check the right OldDbType value is passed.)
NB. the order in the parameters collection determines which parameter matches which ? placeholder. The names given to the parameters are (it seems) ignored.

Inserting data into database (sqlexception) not working

I'm Trying to take data entered by the user from the form view and insert it to the table in a database
The problem is that whenever the compiler reach the Rtype variable to store its value it gives me this error:
I know what the error means but i simply can't get it to work .
The following is my code in the class Form1
Imports System.Data.SqlClient
Public Class Form1`
Private Sub newBtn_Click(sender As Object, e As EventArgs) Handles BtnNwRoom.Click
Dim obj As New Hotl()
Dim selectedItem As Object
selectedItem = hotelCombobox.SelectedItem()
If (obj.addnew(CInt(Me.roomNum.Text), CInt(selectedItem), Me.roomType.Text, Me.price.Text) = False) Then
MsgBox(" no record is added, Try again later")
End If
End Sub
End class
This is the add new function :
Public Function addnew(ByVal roomNo As Integer, ByVal hotelNo As String, ByVal RoomType As String, ByVal price As Integer) As Boolean
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo & " , " & RoomType & " , " & price & ")"
MsgBox(sqlstmnt)
conn = ConNew()
'''''''''''''''''''''''''''''' Execute Reader
''''''''''''''''''''''''''''''''''''''''''''''
Dim command As New SqlCommand(sqlstmnt, conn)
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("insertion Succeded")
Return True
Else
Return False
End If
End Function
As Tim said, use parameterized queries instead.
But, the main cause of your issue is here:
RoomType As String
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo &
" , " & RoomType & " , " & price & ")"
RoomType is defined as a string, but you have no enclosing apostrophes in the Query (hence it will be interpreted as a numeric or a name, not a string.
So, in this particular case, use this:
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo &
" , '" & RoomType & "' , " & price & ")"
But to stress the importance of (among other things) security, use parameterized questions instead and not raw user input directly in the SQL Query.
And just to clarify, here's an example WITH a parameterized Query:
Public Function addnew(ByVal roomNo As Integer, ByVal hotelNo As String, ByVal RoomType As String, ByVal price As Integer) As Boolean
Dim sqlstmnt As String = "INSERT INTO ROOM (roomNo,hotelNo,RoomType,price) VALUES(#roomNo, #hotelNo, #RoomType, #price)"
MsgBox(sqlstmnt)
conn = ConNew()
'''''''''''''''''''''''''''''' Execute Reader
''''''''''''''''''''''''''''''''''''''''''''''
Dim command As New SqlCommand(sqlstmnt, conn)
command.Parameters.Add("#roomNo",SqlDbType.Int).Value = roomNo
command.Parameters.Add("#hotelNo",SqlDbType.Int).Value = hotelNo
command.Parameters.Add("#RoomType",SqlDbType.NVarChar,50).Value = RoomType
command.Parameters.Add("#price",SqlDbType.Int).Value = price
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("insertion Succeded")
Return True
Else
Return False
End If
End Function
Using this code you're protected against SQL Injections and won't have to run into unforseen problems for using reserved Words etc.

Syntax error in update query in VB .NET

I'm trying to run a SQL command in VB .NET but it returns a error message of syntax error in my string variable which I just not able to figure out by myself since this is my first experience for programming with SQL command.The specific message is:
Syntax error (missing operator) in query express '= '045617123'.
Where "045617123" is the data stored in one of the data fields
Can someone please help me out from this? Thank You
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim conobj As New OleDb.OleDbConnection(constr)
Dim da1 As New OleDb.OleDbDataAdapter()
Dim da2 As New OleDb.OleDbDataAdapter()
Dim sqlstr1 As String = ""
Dim sqlstr2 As String = ""
conobj.Open()
For i As Integer = 0 To vt1.Rows.Count - 1
sqlstr1 = "UPDATE Students SET LastName = '" & vt1.Rows(i)(1) & "', FirstName = '" & vt1.Rows(i)(2) & "', StreetAddress = '" & vt1.Rows(i)(3) & "', City = '" & vt1.Rows(i)(4) & "', State = '" & vt1.Rows(i)(5) & "', ZipCode = '" & vt1.Rows(i)(6) & "' WHERE = '" & vt1.Rows(i)(0) & "'"
da1.UpdateCommand = New OleDb.OleDbCommand(sqlstr1, conobj)
da1.UpdateCommand.ExecuteNonQuery()
Next
'For i As Integer = 0 To vt2.Rows.Count - 1
'sqlstr2 = "UPDATE Grades SET FirstExam = " & vt2.Rows(i)(1) & ", SecondExam = " & vt2.Rows(i)(2) & ", FinalExam = " & vt2.Rows(i)(3) & "WHERE StID = " & vt1.Rows(i)(0)
'da2.UpdateCommand = New OleDb.OleDbCommand(sqlstr2, conobj)
'da2.UpdateCommand.ExecuteNonQuery()
'Next
conobj.Close()
End Sub
Use SqlParameters. If some of your datafields contain ' charachter then sql query return a syntax error. Or users can create a Sql injection query.
Your syntax error in the WHERE = '" & vt1.Rows(i)(0) & "'" There are no column name which must be same as datafield value
Here example of using parameters:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim query as New StringBuilder()
With query
.AppendLine("UPDATE Students SET LastName = #LastName")
.AppendLine(", FirstName = #FirstName")
.AppendLine(", StreetAddress = #StreetAddress")
.AppendLine(", City = #City")
.AppendLine(", State = #State")
.AppendLine(", ZipCode = #ZipCode")
.AppendLine("WHERE YourIDField = #ID;")
End With
Using conobj As New OleDb.OleDbConnection(constr)
conobj.Open()
Dim da1 As New OleDb.OleDbDataAdapter()
For i As Integer = 0 To vt1.Rows.Count - 1
Using updCommand As New OleDb.OleDbCommand(query.ToString(), New OleDb.OleDbConnection(""))
updCommand.Parameters.AddWithValue("#LastName", vt1.Rows(i)(1))
updCommand.Parameters.AddWithValue("#FirstName ", vt1.Rows(i)(2))
updCommand.Parameters.AddWithValue("#StreetAddress ", vt1.Rows(i)(3))
updCommand.Parameters.AddWithValue("#City ", vt1.Rows(i)(4))
updCommand.Parameters.AddWithValue("#State ", vt1.Rows(i)(5))
updCommand.Parameters.AddWithValue("#ZipCode", vt1.Rows(i)(6))
updCommand.Parameters.AddWithValue("#ID", vt1.Rows(i)(0))
da1.UpdateCommand = updCommand
da1.UpdateCommand.ExecuteNonQuery()
End Using
Next
End Using
End Sub

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

how oracle read date from basic date picker for vb.net?

hello I'm using oracle & vb.net
this is my code for select statement and I want to display the selected date from interface which i use Basic Date Picker and i assign that as bdp1
Dim queryString As String = "select * from abc where (tran_dttm <= to_date( '" & bdp1 & "' ,'MM/DD/YYYY') and tran_dttm > to_date( '" & bdp1 & "' ,'MM/DD/YYYY')and lpt = '" & ListBox1 & "' and device = '" & strMaterial & "')"
select * from abc where trunc (tran_dttm) = to_date('" & bdp1 & "','MM/DD/YYYY')
Parameters should be prefixed with the : and should be included as text directly in the command. It is the job of the framework to pass them with their values to the database engine
Private Function GetDate(ByVal strMaterial As String, ByVal ListBox1 As String, ByVal bdp1 As Date) As DataSet
Dim connectionString As String = "Data Source = ***; User ID = ***; Password = **;"
Dim queryString As String = "BEGIN select * from abc " & _
"where (tran_dttm <= to_date(:bdp1,'MM/DD/YYYY') and " & _
"tran_dttm > to_date(:bdp1 ,'MM/DD/YYYY') and " & _
"lpt = :lb1 and device = :mat); END;"
Using sqlConnection = New OracleClient.OracleConnection(connectionString)
Using sqlCommand = New OracleClient.OracleCommand(queryString, sqlConnection)
sqlCommand.CommandTimeout = 0
sqlCommand.Parameters.Add(New OracleParameter(":bdp1", OracleType.DateTime)).Value = bdp1
sqlCommand.Parameters.Add(New OracleParameter(":lb1", OracleType.VarChar)).Value = lstBox1.SelectedItem.ToString
sqlCommand.Parameters.Add(New OracleParameter(":mat1", OracleType.VarChar)).Value = strMaterial
Dim dataAdapter As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(sqlCommand)
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
Return dataSet
End Using
End Using
End Function
The ListBox1 is wrong if it is a control. You should use the SelectedItem property as value for the parameter (a bit of error checking is needed though)