Syntax Error OledbException delete statement - vb.net

I can't fugure out what my syntax error is here. Anyone spot it? Or am I going about this all wrong?
Dim myCommand As New OleDb.OleDbCommand("delete * from Team where intPlayerNo='" & txtUniformNo.Text & "'_ strFirstName='" & txtFirstName.Text & "'_ strLastName='" & txtLastName.Text & "'_ strParentName='" & txtParent.Text & "'_ strAddress='" & txtAddress.Text & "'_ strCity='" & txtCity.Text & "'_ strState='" & txtState.Text & "'_ strZipCode='" & txtZip.Text & "'_ strPhone='" & txtPhone.Text & "'_ intAge='" & txtAge.Text & "'", myConnection)

A delete statement is Delete From Team Where...
You would be best advised to use Parameterized Queries to avoid SQL Injection Attacks

Your syntax is wrong because you have multiple WHERE conditions but you don't use the correct AND/OR to connect the conditions together. Of course the DELETE * FROM table syntax is accepted only by MS-ACCESS, but the correct SQL syntax is DELETE FROM (without the *) and is accepted also by Access so it is better to use the standard.
Said that you need to use a parameterized query in your command and not a string concatenation
Dim cmdText = "DELETE FROM Team " & _
"WHERE intPlayerNo = #playerNo AND " & _
"strFirstName = #firstName AND " & _
".... and so on with the other fields "
Dim myCommand As New OleDb.OleDbCommand(cmdText, myConnection)
myCommand.Parameters.Add("#playerNo", OleDbType.VarWChar).Value = txtUniformNo.Text
myCommand.Parameters.Add("#firstName", OleDbType.VarWChar).Value = txtFirstName.Text
... continue with the other parameters required by the WHERE statement
myCommand.ExecuteNonQuery()
Using parameters will keep your code safe from Sql Injection and avoid syntax errors if some of your textbox values contains a single quote.
Keep in mind that if your table has a primary key, then your WHERE could simply reduced to only the PrimaryKeyFieldName = #Value

Related

Ignore apostrophe in sql query from text box

I'm thoroughly enjoying my stay here at stack overflow, I have found more useful information than I can count.
However, through all of my searches, I have yet to find an answer to my issue.
I have a Winforms app that inputs data into an SQL database. I have an issue with the text box in this form posting to the database.
If a user inputs an apostrophe or a quotation mark the query in Visual studio stops at where that apostrophe is in the text box even if there is more data after that and does not enter the data into the database.
I know that putting a second apostrophe will cancel out the one that was input, however, I can't seem to read the data in the text box before the query executes to cancel them out. I have put an example of what works in this text box and what breaks the query in this question for further clarification.
I apologize, everyone, it seems I forgot to put my code into this post.
Dim InsertQuery As String = "INSERT INTO SelfInstallNotes (Troubleshooting, DateAndTime, [CL to OD], [Swapped Dscntd Clocks], [Upgrading to SaaS], [Update Version], [Created RPF], [Created RMA], [Clock Serial], [Case Number], [User], [Grabbed], [Account Manager], [Transferred to AM]) VALUES('" & Hidden.TextBox6.Text.ToString & "'" & "," & "'" & DateTimePicker1.Value & "'" & "," & "'" & CheckBox1.CheckState & "'" & "," & "'" & CheckBox2.CheckState & "'" & "," & "'" & CheckBox3.CheckState & "'" & "," & "'" & CheckBox4.CheckState & "'" & "," & "'" & CheckBox5.CheckState & "'" & "," & "'" & CheckBox6.CheckState & "'" & "," & "'" & TextBox2.Text & "'" & "," & "'" & TextBox1.Text & "'" & "," & "'" & TextBox6.Text & "'" & "," & "'" & Hidden.TextBox3.Text & "'" & "," & "'" & Hidden.TextBox4.Text & "'" & "," & "'" & Hidden.TextBox5.Text & "'" & ")"
But after reading all of you answers this code is most certainly WRONG and can cause issues later on down the road. I will try the answer posted below and update the thread accordingly.
This query will not post to DB due to the apostrophe in can't
while this input in the textbox will post without any issues, as there is no apostrophe or quotation marks.
The problem is worse than you know. This is also a huge security issue. Try putting the following text in your input:
'; DROP TABLE [MyCallTable];--
Or don't, if you value your data.
Fortunately, the solution is the same for both the security issue and for normal, everyday apostrophes; you quarantine all user input from the rest of the SQL command by using query parameters.
Here's an example:
var SQL = "SELECT * FROM Users WHERE LastName = #LastName";
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(SQL, cn))
{
//TextBox1 can have text with ' characters, and it won't matter.
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 25).Value = TextBox1.Text;
cn.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
}
There are other forms of this, too, depending on your environment, but the important thing is the text input is never at any time substituted directly in the SQL command — not even on the database server. This prevents any possibility of bad input injecting into the SQL. It also makes it easier to get things like date formats right, as now the ADO.Net provider will handle conversions for you.
The main thing to understand is if you ever find yourself doing anything like this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text + "'";
or even this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text.Replace("'", "''") + "'";
you're doing something very wrong.
This is one of those things that's important enough it's worth going back through an old code base to fix every instance where you've done it the wrong way before the next release, and it's not often I'll say that.
var stringvariable = tempString.Replace("'", "''");// this escapes the single quote

VB 2012 error message

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.

Cannot insert records to ms access 2007 with vb6

I have been searching around for the proper way of connecting into the database(MS ACCESS 2007) using VB6.0... The problem is it says an error that "SYNTAX ERROR IN INSERT INTO STATEMENT"
DECLARATION CODE:
Dim adoConn As New ADODB.Connection
Dim adoRS As New ADODB.Recordset
Dim conStr, sqlStr As String
CONNECTION CODE:
conStr = "Provider=Microsoft.Jet.OLEDB.3.51;Data Source= " & App.Path & "\curriculum.mdb;Persist Security Info=False"
Set adoConn = New ADODB.Connection
adoConn.ConnectionString = conStr
adoConn.Open
Here is the BUTTON code:
sqlStr = "INSERT INTO cur(CourseCode, Units, Days, Time, RoomNumber, Instructor, Course, YearLevel, Term) VALUES ("
sqlStr = sqlStr & "'" & txtCurCourseCode.Text & "',"
sqlStr = sqlStr & "'" & txtCurUnits.Text & "',"
sqlStr = sqlStr & "'" & txtCurDays.Text & "',"
sqlStr = sqlStr & "'" & txtCurTime.Text & "',"
sqlStr = sqlStr & "'" & txtCurDays.Text & "',"
sqlStr = sqlStr & "'" & txtCurRoom.Text & "',"
sqlStr = sqlStr & "'" & txtCurInstructor.Text & "',"
sqlStr = sqlStr & "'" & cboCurCourse.Text & "',"
sqlStr = sqlStr & "'" & txtCurYearLevel.Text & "',"
sqlStr = sqlStr & "'" & txtCurTerm.Text & "')"
adoConn.Execute sqlStr
THE ERROR IS FOUND IN THIS LINE OF CODE WHEN I CLICK DEBUG: adoConn.Execute sqlStr
YOUr help would be greatly appreciated as this school project is needed by tomorrow. Been sleepless for many nights. thansk
Unfortunately, you are using duplicate value..
I mean yor are trying to INSERT INTO to 9 columns(CourseCode, Units, Days, Time, RoomNumber, Instructor, Course, YearLevel, Term), however, you are putting 10 values().
txtCurDays is duplicated.
That error indicates the generated SQL statement has an error in it.
Set a breakpoint on the line:
adoConn.Execute sqlStr
Then view the SQL query (print it to the immediate window or just examine it in the locals window). Check for any syntax errors.
One likely errore in your SQL would be a apastrophe (') in one of your text fields. You need to make sure you "escape" any apostrophes in your SQL statement. You can do this easily by tweaking your code a bit like so:
sqlStr = sqlStr & "'" & Replace(cboCurCourse.Text, "'", "''") & "',"
Escape the column names that match reserved words: TIME by enclosing in []:
sqlStr = "INSERT INTO cur(CourseCode, Units, Days, [Time], RoomNumber, Instructor, Course, YearLevel, Term) VALUES ("
You should also use paramaterized queries as what you have in vulnerable to SQL Injection. (Run with a ' in one of the textboxes)

Conversion failed when converting date and/or time from character string

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

how to store data from vb.net to access a database

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.