I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:
Dim sql As String
sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
"','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
"','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
cmmd = New OleDbCommand(sql, cnn)
The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:
Dim sql As String = _
"INSERT INTO tcekin " &_
"(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
"VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...
This will also make it easier to spot and avoid syntax errors like the one you're complaining about.
Related
I'm using Microsoft Visual Studio 2010 Express and I'm trying to make a enrollment form using VB.NET. This is my code so far:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cardStr As String
Dim formStr As String
Dim birthStr As String
Dim goodmoralStr As String
If cbcard.Checked Then
cardStr = "OK"
Else
cardStr = ""
End If
If cbform.Checked Then
formStr = "OK"
Else
formStr = ""
End If
If cbbirth.Checked Then
birthStr = "OK"
Else
birthStr = ""
End If
If cbgoodmoral.Checked Then
goodmoralStr = "OK"
Else
goodmoralStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection(conStr)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into tblEnroll(StudID,StudLevel,StudFName,StudMName,StudLName,StudGender,StudBirthday,StudNationality,StudContact,StudPOB,StudCitizenship,StudReligion,MomName,MomContact,MomOccupation,DadName,DadContact,DadOccupation,PrevSchool,Card,F137,BirthCertificate) values ('" & txtID.Text & "','" & lbGrade.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & txtLName.Text & "','" & lbGender.Text & "','" & dtpBirthDate.Text & "','" & txtNationality.Text & "','" & txtStudContact.Text & "','" & txtPOB.Text & "','" & txtCitizen.Text & "','" & txtReligion.Text & "','" & txtMom.Text & "','" & txtMomContact.Text & "','" & txtMomOccupation.Text & "','" & txtDad.Text & "','" & txtDadContact.Text & "','" & txtDadOccupation.Text & "','" & txtPrevSchool.Text & "','" & cardStr & "','" & formStr & "','" & birthStr & "','" & goodmoralStr & "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Student Successfully Enrolled!")`
What could be the solution here?
You have one too many columns in your INSERT statement values. The value goodmoralStr does not have a corresponding column to insert into.
As a slight aside, you really should use parameterised SQL in your code to avoid issues with SQL injection.
I am doing a project in vb.net and I've made a table with listview now the problem is that I am not be able to get a specific column item and only be able to get the item of first column (listview.selecteditems(0).text) and i.e. 0(zero)... ListView1.SelectedItems(1/2/3/so on).Text is not working.
My code is:
s = one_way.ListView1.SelectedItems(4).Text
cmd1 = New OleDbCommand("Select reference_no from Booking_Details", cn)
cmd1 = New OleDbCommand("insert into Booking_Details values(" & i & ",'" & one_way.ListView1.SelectedItems(0).Text & "','" & main.ComboBox1.Text & "','" & main.ComboBox9.Text & "','" & main.RadioButton2.Text & "','" & main.ComboBox2.Text & "','" & main.ComboBox4.Text & "','" & main.DateTimePicker2.Text & "','" & s & "',' ',' ','" & main.ComboBox5.Text & "','" & main.ComboBox6.Text & "','" & main.ComboBox7.Text & "')", cn)
cmd1.ExecuteNonQuery()
s = one_way.ListView1.SelectedItems(4).Text
cmd1 = New OleDbCommand("Select reference_no from Booking_Details", cn)
cmd1 = New OleDbCommand("insert into Booking_Details values('" & s & "')", cn)
cmd1.ExecuteNonQuery()
Someone please help.
In a listview, selecteditem(s) refers to the row. In order to add columns to it, you had to create and assign subitems and that is how you need to get the info back:
someInfo = listview.SelectedItems(X).SubItems(Z).Text
'SelectedItems(N).Text' is just returning the column 0 or item text.
your code is also ripe for a sql injection attack - you should use parameters: https://stackoverflow.com/a/16760887/1070452
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & "values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',convert(date,'" & DateTimePicker1.Value & "',103),convert(date,'" & DateTimePicker2.Value & "',103),'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
You should use sql-parameters to avoid sql-injection and to prevent from conversion issues like this.
Example presuming SQL-Server:
Const sql = "INSERT INTO tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)" & vbCrLf & _
"VALUES(#nurseid, #nursename, #deptname, #dob, #doj, #qualification, #salary)"
Using con = New SqlConnection("Insert Your Connection String Here")
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#nurseid", txtNurseid.Text)
cmd.Parameters.AddWithValue("#nursename", TxtNursename.Text)
cmd.Parameters.AddWithValue("#deptname", Cmbdept.Text)
' -- No conversion problems anymore because you pass a DateTime -- '
cmd.Parameters.AddWithValue("#dob", DateTimePicker1.Value)
' ... other parameters ... '
con.Open()
Dim affectedRecords As Int32 = cmd.ExecuteNonQuery()
End Using
End Using
Try to change like this ..
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & " values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',#" & format(DateTimePicker1.Value.Date) & "#,#" & format(DateTimePicker2.Value.Date) & "#,'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
As Tim Scmelter said .. you better use parameterize input
Add Parameters as below and it works like charm
cmnd.Parameters.Add("#date_time", SqlDbType.DateTime).Value = datetime.Date;
The original post is here:
https://www.codeproject.com/Answers/552202/Conversionplusfailedpluswhenplusconvertingplusdate#answer3
am new to vb.net i have a project vb.net connect to access 2003 database and i want to insert data through vb.net to access data base am using Sql commands here is the code bt it's not working for me
cmd.CommandText = "INSERT INTO info(nam, employed, ple, mertebe, navonishan, sermoche, moche, dxindin, dbemoche, brwaname)" + " VALUES (" & Me.NamTextBox.Text & ",'" & CDate(Me.EmployedDateTimePicker.Text) & "','" & CInt(Me.PleTextBox.Text) & "','" & CInt(Me.MertebeTextBox.Text) & "','" & Me.NavonishanTextBox.Text & "','" & CDate(Me.SermocheDateTimePicker.Text) & "','" & CInt(Me.MocheTextBox.Text) & "','" & CByte(Me.DxindinCheckBox.Checked) & "','" & CByte(Me.DbemocheCheckBox.Checked) & "','" & Me.BrwanameTextBox.Text & "' );"
Use parametrized query.
cmd.CommandText = "INSERT INTO info(nam, employed, ple, mertebe, navonishan, " & _
"sermoche, moche, dxindin, dbemoche, brwaname) VALUES (" & _
"?,?,?,?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("#p1", Me.NamTextBox.Text)
cmd.Parameters.AddWithValue("#p2", Convert.ToDateTime(Me.EmployedDateTimePicker.Text))
cmd.Parameters.AddWithValue("#p3", Convert.ToInt32(Me.PleTextBox.Text))
cmd.Parameters.AddWithValue("#p4", Convert.ToInt32(Me.MertebeTextBox.Text))
cmd.Parameters.AddWithValue("#p5", Me.NavonishanTextBox.Text)
cmd.Parameters.AddWithValue("#p6", Convert.ToDateTime(Me.SermocheDateTimePicker.Text))
cmd.Parameters.AddWithValue("#p7", Convert.ToInt32(Me.MocheTextBox.Text))
cmd.Parameters.AddWithValue("#p8", Me.DxindinCheckBox.Checked)
cmd.Parameters.AddWithValue("#p9", DbemocheCheckBox.Checked)
cmd.Parameters.AddWithValue("#p10", Me.BrwanameTextBox.Text)
A part from the string concatenation, in this way you don't risk to pass a value intended to be a number or a date with the wrong formatting rules (your numeric or date values should not be enclosed in single quotes).
Of course this avoid also the Sql Injection problems stated by other (Cody Gray) in comment
I don't know how to avoid SQL injection, could someone help me with my problem?
Here is my current code:
Private Function INSERT() As String
Dim SQLcon As New SqlConnection
Dim SQLdr As SqlDataReader
Try
SQLcon.ConnectionString = "Data Source=#####;Initial Catalog=OJT;Persist Security Info=True;User ID=####;Password=#####"
Dim SQLcmd As New SqlCommand("INSERT INTO dbo.Patients(pIDNo,pLName,pFName,pMI,pSex,pStatus,pTelNo,pDocID,pAddr,pStreet,pBarangay,pCity,pProvince,pLNameKIN,pFNameKIN,pMIKIN,pRelationKIN) VALUES('" & LabelPNumber.Text & "','" & txtLname.Text & "','" & txtFname.Text & "','" & txtMI.Text & "','" & txtPatientSex.Text & "','" & txtPatientSex.Text & "','" & txtPatientTelNo.Text & "','" & txtPatientDoctor.Text & "','" & txtStreetNumber.Text & "','" & txtStreetName.Text & "','" & txtBarangay.Text & "','" & txtCity.Text & "','" & txtProvince.Text & "','" & txtKinLname.Text & "','" & txtKinFname.Text & "','" & txtKinMI.Text & "','" & txtRelationToPatient.Text & "') ", SQLcon)
SQLcon.Open()
MsgBox("Patient Added!", MsgBoxStyle.Information)
SQLdr = SQLcmd.ExecuteReader()
Catch ex As Exception
MessageBox.Show("Error Occured, Can't Add Patient!" & ex.Message)
Finally
SQLcon.Close()
End Try
Return "done"
End Function
Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.
Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd here).
I'll show you an example with one of your parameters - change your SQLCommand text to:
INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(#pIDNo, ...)
Where #pIDNo is a "placeholder" in the string for the parameter value, which is sent separately from the command in the SQLParameters collection.
Then you can add a parameter with the same name as this "placeholder", and the value (it will derive the type from the value provided for you).
Here's the example from earlier:
SQLcmd.Parameters.AddWithValue("#pIDNo", LabelPNumber.Text)