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)
Related
This is my Code I want to Enter First_Name,Middle_name and Last_Name in one Fieldname
Try
MysqlConn.Open()
Dim Query As String
Query = "INSERT INTO residentrecords.info (id,last_name,first_name,middle_name,age,address,contact_no,date_of_birth,religion,civil_status,education_attainment,occupation,fathers_name,mothers_name,mothers_occupation,fathers_occupation,gender,purok,blotter,docu,voter) values ('" & add.TextBox_ID.Text & "','" & add.TextBox_LN.Text & "','" & add.TextBox_FN.Text & "','" & add.TextBox_MN.Text & "','" & add.TextBox_Age.Text & "','" & add.TextBox_Address.Text & "','" & add.TextBox_Contact.Text & "','" & add.DateTimePicker1.Text & "','" & add.ComboBox_religion.Text & "','" & add.ComboBox_CS.Text & "','" & add.TextBox_Educ.Text & "','" & add.TextBox_Occu.Text & "','" & add.TextBox1_FathersName.Text & "','" & add.TextBox1_MothersName.Text & "','" & add.TextBox_mothersocc.Text & "','" & add.TextBox_fathersocc.Text & "','" & add.ComboBox_gender.Text & "','" & add.rpurok.Text & "','0','0','" & add.voter.Text & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Successfully Registered!", "REGISTERED", MessageBoxButtons.OK, MessageBoxIcon.None)
If vbOK = MsgBoxResult.Ok Then
Me.Dispose()
add.Dispose()
add.Enabled = True
residents.Show()
End If
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
That's quite easy in .net. You need to split one string on it's whitespaces and insert the substrings seperately.
Use somethiing like this
Dim names as String()
Dim firstName as String
Dim middleName as String
Dim lastName as String
names = add.TextBox_Name.Text.Split(" ")
firstName = names(0)
middleName = names(1)
lastName = names(2)
You might check the array length by forehand to make sure the user really has a middle name. Or even more than one. I have two. Just check for names.length.
I hope i didn't misinterpreted your question. It was quite short explained.
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
con.Open()
cmd.CommandText = "Insert Into tblEmp (FN,MN,LN,PAddHN,PAddSB,PAddMun,VPA,BD,BP,Tel,Rel,Cit,Height,Weight,Gend,SN,SOcc,NoC,AgeC,Stat,DS,FaN,FaOcc,MaN,MaOcc,PAdd,PTCN,PTCP,SSS,TIN,PHILH,PAGIBIG,CPNo,Sued,Age,BankAcc,empRfID,Principal,Department,Position,DRate,empID,OffT) Values('" & zfn & "','" & zmn & "','" & zln & "','" & zpaddhn & "','" & zpaddsb & "','" & zpaddmun & "','" & zvpa & "','" & zbd & "','" & zbp & "','" & ztel & "','" & zrel & "','" & zcit & "','" & zheight & "','" & zweight & "','" & zgend & "','" & zsn & "','" & zsocc & "','" & znoc & "','" & zagec & "','" & zstat & "','" & zds & "','" & zfan & "','" & zfaocc & "','" & zman & "','" & zmaocc & "','" & zpadd & "','" & zptcn & "','" & zptcp & "','" & zsss & "','" & ztin & "','" & zphilh & "','" & zpagibig & "','" & zcpno & "','" & zsued & "','" & zage & "','" & txtBankAcc.Text & "','" & zempRefID & "','" & cmbPrin.SelectedItem & "','" & cmbDept.SelectedItem & "','" & txtPos.Text & "','" & txtDRate.Text & "','" & empID & "','" & zOffTime & "')"
cmd.ExecuteNonQuery()
con.Close()
I got an error when running this in my program.. but when i paste the command in my ms access query and it runs successfully. is there any problem in my code? Pls help tnx.
where is your add parameter value?
You can try this
Try
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dir\DB.accdb")
Dim command As String
command = "INSERT INTO Table (NOTIF, EMP_NO, EMP_NAME, [POSITION]) VALUES (#NOTIF, #EMP_NO, #EMP_NAME, #POSITION)"
con.Open()
Dim cmd As OleDbCommand
cmd = New OleDbCommand(command, con)
cmd.Parameters.AddWithValue("#NOTIF", NOTIFTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NO", EMP_NOTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NAME", EMP_NAMETextBox.Text)
cmd.Parameters.AddWithValue("#POSITION", POSITIONTextBox.Text)
cmd.ExecuteNonQuery()
Catch exceptionObject As Exception
MessageBox.Show(exceptionObject.Message)
Finally
con.Close()
End Try
this code i have used before, it work perfectly
Also your name of the field look like contain illegal value to VB.net, so must like this
[Height],[Weight],.... You can try to check it in you DATASET > Configure > Select Statement > Insert and you will look the illegal value.
Just like my POSITION field, it was illegal, so must contain "[]"
You may not use the "'", if the datatype is something like numbers. If i interprete it correctly, some of your fields are numbers.
con.Open()
cmd.CommandText = "Insert Into tblEmp (someInt, someString) VALUES (12, 'asdf')"
cmd.ExecuteNonQuery()
con.Close()
Beside this, you should get the same error in Acces, if you run you Query again. Use the debugger and add a Breakpoint at the "cmd.ExecuteNonQuery()" to get the finished query command string with all "'".
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.