I get the following error: Operator '&' is not defined for types 'String' and 'System.Windows.Forms.TextBox'. :
in the following line of code:
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
here is the code :
Private Sub addbtn_Click(sender As Object, e As EventArgs) Handles addbtn.Click
Dim cmd As New OleDbCommand
If Not connection.State = ConnectionState.Open Then
connection.Open()
End If
cmd.Connection = connection
' add data to table
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
cmd.ExecuteNonQuery()
'refresh data in list
'close connection
connection.Close()
End Sub
You have to use Me.adduseridtxtbox.Text (which gets the value of the TextBox) rather than the TextBox directly.
Also, please, please, please read about OleDbParameter and how to use these parameters with OleDbCommand to prevent injection. Microsoft even provides examples.
Currently your code is extremely dangerous if you are letting users fill this form out themselves, as they have full control over your database. Regardless, using OleDbParameter is a good practice to get into. You appear to be handling social security numbers here -- your users deserve some form of security.
You should try to use/declare parameters in your query.
For example:
cmd.CommandText = ("INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) " & _
"VALUES (#uid, #pw, #fn, #ln, #job, #ssn)")
With cmd.Parameters
.Clear()
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("pw", addpasswordtxt.Text
.AddWithValue("fn", addfirstnametxt.Text)
.AddWithValue("ln", addlastnametxt.Text)
.AddWithValue("job",jobcbox.SelectedValue)
.AddWithValue("ssn", addssntxt.Text)
End With
cmd.ExecuteNonQuery()
Your SQL Statement is not proper. How do you use an object as a string? It should be
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES ('" & Me.adduseridtxtbox.Text & ",'" & Me.addpasswordtxt.Text & ",'" & Me.addfirstnametxt.Text & ",'" & Me.addlastnametxt.Text & ",'" & Me.jobcbox.Text & ",'" & Me.addssntxt.Text & "')"
Use parametrised query to prevent SQL Injections and make safe your database system from malicious users.
Related
When trying to copy data from an Excel userform in to an Access table via SQL I am encountering an error on a field that is a Yes/No type in the database. How can I format the info correctly so that it updates the database?
I have looked at some other examples of copying data into the Yes/No fields in Access, as well as trying my code in a number of different formats, with double quotations, single quotations & as it appears below
Dim oConn As ADODB.Connection
Dim oCm As ADODB.Command
Dim iRecAffected As Integer
If Me.TBField.Visible = False Then
'Update office users
Init1 = Left(Me.TxtName1, 1) & Mid$(Me.TxtName1, InStr(Me.TxtName1, " ") + 1, 1)
Select Case Me.LblFraOffice.Caption
Case Is = "Add User"
Set oConn = New ADODB.Connection
oConn.Open sConn
Set oCm = New ADODB.Command
oCm.ActiveConnection = oConn
If RbUser.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, User, JobRole) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbAdmin.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbManager.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
End If
'MsgBox oCm.CommandText
oCm.Execute iRecAffected
oConn.Close
When pressing submit on the userform this should add a newly created user into the database table. If I remove the User field (and the associated true/false) it works. But my users can be users, admins or managers
At present I receive an error message
Run-time error '-2147217900 (80040e14)': Syntax error in INSERT INTO statement
Column name User is the reserved keyword. Can you add square brackets around the keyword to fix the issue:
INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, [User], JobRole)
or you can rename the column name to a non-reserved keyword to sovle this error.
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
When the code is executed and error is thrown, but there is no visible problem that i can see. Help!
The word PASSWORD is reserved in MS-Access.
You need to use square brackets around that name (Or change it to something different)
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (......
Said that, please use a parameterized query to build sql commands.
A string concatenation like yours is easily attacked by hackers using SQL Injection
Also, if the username or password contains a single quote, the resulting sql text built using string concatenation will be invalid.
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (?, ?)"
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
cmd.Parameters.AddWithValue("#p1",txtUsername.Text);
cmd.Parameters.AddWithValue("#p2",txtEncryptedPassword);
cmd.ExecuteNonQuery();
You forgot parentheses:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
try this code:
Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonCode _
& "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')"
Do it like that but change to your names.
Declare the values of text boxes as strings and just use those.
your doing () this mistake and you should must add:
your code:
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
you should must change code following as:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
update1:
"INSERT INTO `test`.`users` ( `username`, `password`) " & _
"VALUES ('" & txtUsername.Text & "', '" & txtPassword.Text & "');"
update2:
"INSERT INTO users ( `username`,`password`)VALUES(#txtUsername.Text,#txtPassword.Text);"
"INSERT INTO users (Username,Password)VALUES(?,?);"
note:test means database name you should change your databasename.
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)
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.