System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.' / cmd.ExecuteNonQuery() - sql

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If NamaBukuBox.Text = " " Or PngrngBukuBox.Text = " " Or PnrbtBukuBox.Text = " " Or JmlhBukuBox.Text = " " Then
MsgBox("Isi Semua Kolom Informasi")
Else
Con.Open()
Dim query = "Insert into BukuTbl values('" & NamaBukuBox.Text & "','" & PngrngBukuBox.Text & "','" & PnrbtBukuBox.Text & "'," & JmlhBukuBox.Text & ")"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, Con)
cmd.ExecuteNonQuery() '** this line is error
MsgBox("Buku Telah Ditambahkan")
Con.Close()
End If
End Sub
I don't know what to do
what makes the error and how to solve it?

This is a very risky way of writing code. User input would be inserted directly into SQL. If your user inputs any apostrophe, your SQL will fail.
For example, try entering Abc's into the NamaBukuBox text box. Check your resulting SQL. In the worst case scenario, a user could inject SQL and delete data and tables.
In your case, it is likely the input from the user that is causing the SQL to fail. Please use parameters to input user data into SQL. Do not concatenate user input direct in SQL. You SQL should look something like:
Insert into BukuTbl values(#NamaBukuBox,#PngrngBukuBox,#PnrbtBukuBox,#JmlhBukuBox)

Related

Er : Syntax error in INSERT INTO statement Visual Basic 2017 using MC Access 2016 , oleDb 4.0

I am trying to insert data in my access database but i am getting a Syntax error in INSERT statemnt exception.Can someone please help me troubleshoot this error...Maybe my inset statement is not correct ?
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If cmbTo.Text = "" Or cmbfrom.Text = "" Or cmbDay.Text = "" Or cmbMonth.Text = "" Or cmbYear.Text = "" Or cmbListBus.Text = "" Then
MsgBox("Please Insert Your Destination")
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hacke\source\repos\Student\Database\studentdatabase.mdb")
Dim insert As String = "INSERT INTO [BUSTICKET] VALUE ('" & cmbfrom.Text & "','" & cmbTo.Text & "','" & cmbDay.Text & "','" & cmbMonth.Text & "','" & cmbYear.Text & "','" & cmbListBus.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Success")
conn.Close()
End If
Catch ex As Exception
MsgBox("Err : " & Err.Description)
End Try
End Sub
End Class
A few mistakes in your post has made it a bit difficult for us to understand.Anyway,i've submitted an edit of your post.
The problem i see so far is that you haven't defined which table you want to insert the data in.For example,if your table name is Students ,then a sample sql/OleDb statement might look like
"Seletct * from Students",ConnectionString
Note : In the following statement,i used (*) which means i am not selecting/targeting any particular column/cell but all the columns/cells.This statement is used for various purposes specially when retrieving data from the database.
However,your motive is to insert data in the database.
The INSERT statement for any database software(AFAIK) must include the Table name you are targeting,the Column/Cell headers/names.Let's assume your Table name is Students and you want to insert data in FirstName,LastNmae columns.Then a sample Insert statement may look like :
"Insert into Students(FirstName,LastName)values(#fname,#lname)", ConnectionString
Now,NOTE THAT i am not adding the values directly in the statement.you can do that if you want.However,in this sample insert statement,i am rather defining some parameter names like#Fname and #Lname.This will be used later on to finally insert data into the table's columns.
Now,if you go with my sample code,you must assign some values to these parameters from your application.We have 2 parameters now and they are #Fname and #Lname.We now need to add literal values to them.Let's assume the values are coming from TextBoxes.
MyOledbCommand.Add("#Fname",OledbDatatype.VarChar).Value = FNameTxtBox.Text
'Or you can use :
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
After you are done assigning the textboxes(or some string or whatever) as the values,it is time to execute the command so that the data inserts.For that,we generally call :
MyOleDbCommand.ExecuteNonQuery()
So,here's a full sample :
Dim con as New oleDbConnection = "ConnectionStringHere"
Con.open
Dim MyOleDbCommand as new OleDbCommand("Insert into Students(FirstName,LastName)values(#fname,#lname)", con)
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
MyOledbCommand.AddWithValue("#Lname",LNameTxtBox.Text)
MyOleDbCommand.ExecuteNonQuery
Con.Close
Hope this helps :)

Im trying to INSERT data on a database with VB

I'm trying to Insert data on a access DataBase using Visual Basic with OleDbCommand, but it keeps returning me this error:
Here's my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myconnection.ConnectionString = connString
Dim sql As String
myconnection.Open()
sql = "INSERT INTO Atletas ( Nome, Contacto, Email, dataNascimento, Morada, idEscalao ) VALUES( " & Text_Nome.Text & "','" & Text_Contacto.Text & "','" & Text_Email.Text & "','" & Data_Picker.Text & "','" & Text_Morada.Text & "','" & Combo_Escalao.Tag & ")"
Dim cmd As OleDbCommand = New OleDbCommand(sql, myconnection)
cmd.ExecuteNonQuery()
myconnection.Close()
End Sub
Firstly, I suggest you take a serious look at using parameters. As you can see, had you been using parameters you would not have had the syntax error. It will also eliminate problems with names such as O'Hara or O'Kelly as Steve pointed out.
Secondly It also protects you from SQL injection attacks - see Bobby Tables.
Finally, implementing a using block is good practice when it comes to using database connections, just in case you forget to close a connection, it will be disposed of at the end of the using block.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = database path here"
con.Open()
Dim sql As String = "INSERT INTO Atletas (Nome, Contacto, Email, dataNascimento, Morada, idEscalao) VALUES (#nome, #contacto, #email, #datanascimento, #morada, #idescalao);"
Dim sql_insert As New OleDbCommand
With sql_insert
.Parameters.AddWithValue("#nome", Text_Nome.Text)
.Parameters.AddWithValue("#contacto", Text_Contacto.Text)
.Parameters.AddWithValue("#email", Text_Email.Text)
.Parameters.AddWithValue("#datanascimento", Data_Picker.Value.ToString("yyyy/MM/dd")) '''Assuming the value needed is a date only
.Parameters.AddWithValue("#morada", Text_Morada.Text)
.Parameters.AddWithValue("#idescalao", Cstr(Combo_Escalao.Tag))
.CommandText = sql
.Connection = con
.ExecuteNonQuery()
End With
con.close()
End Using
End Sub
You are missing two apostrophes, one at the beginning and another at the end. It's also good practice to end it with a semicolon. Try this:
sql = "INSERT INTO Atletas ( Nome, Contacto, Email, dataNascimento, Morada, idEscalao ) VALUES( '" & Text_Nome.Text & "','" & Text_Contacto.Text & "','" & Text_Email.Text & "','" & Data_Picker.Text & "','" & Text_Morada.Text & "','" & Combo_Escalao.Tag & "');"
However, as Plutonix suggested in his comment: Do Not concat string to make SQL. Use SQL parameters.

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

ASP.NET(VB) How to insert textbox.text into SQL database?

I am designing a register form.
The following is my codes:
but after I do it, then the SQL table display is not the user's data....?
The database table display &username&, &password&
(username, password...are textboxes name)
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection(".....")
Conn.Open()
Dim sqlstr As String = "Insert Into user_profile(username,password,nickname,realname,email) Values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text & "')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
Ok, first, I'll take a stab at your question. Then, we NEED to talk about SQL Injections.
Try this:
Dim MyValues as String = String.Format("'{0}', '{1}', '{2}', '{3}', '{4}'", username.Text, password.Text, nickname.Text, realname.Text, email.Text )
Dim sqlstr As String = "Insert Into user_profile(username,password,nickname,realname,email) Values(MyValues)"
(I've not tested that code. Watch for syntax errors.)
Now, that having been said, it is VITAL that you understand the danger of the way you are trying to do this. The serious problem here is that you are wide open to a SQL Injection attack. Google it. But in short, using this approach, someone can put commands like 'drop table' into your textbox, and those commands will be executed in your database.
The proper way to do this would be to create a stored procedure that contains the INSERT statement, and then pass your values to it with parameters. The web is littered with tutorials on how to do this. You'll find one easy enough.
Good luck!

Trying to update record, keep getting this error vb.net

I'm sure this question will be easy for you lot... :)
I'm simply trying to update an existing record in my database using the following:
Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.Click
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd2.Connection = cnn
cmd2.CommandText = "UPDATE HireItemRecord SET HireItemBeginDate = " & TextBox45.Text & _
" ,HireItemEndDate = " & TextBox44.Text & _
" ,HireItemCost = " & TextBox16.Text & _
" ,PaymentMethod = " & TextBox17.Text & _
" ,Staff_Id = " & TextBox19.Text & _
" ,HireItemNotes = " & TextBox18.Text & _
" ,HireItemReturnDate = " & TextBox43.Text & _
"WHERE HireRecord_Id = " & TextBox13.Text
cmd2.ExecuteNonQuery()
ds1.Clear()
daHireItemRecord.Fill(ds1, "PersonDetails")
cnn.Close()
End Sub
However no matter what record is selected and whatever details are in the boxes I keep getting this same error over and over:
SqlException was unhandled
Incorrect syntax near '12'.
When there is absolutely nothing in the textboxes the error changes to:
Incorrect syntax near ','.
I'm very new to this and I just can't seem to understand why this is happening.
Thank you very much for your help. :)
So much wrong with this.
You need a space after each comma, not before it.
You should be escaping your values before using them in the query. If I put "0 WHERE 1=1 -- " in any of your text boxes, it'll trash your entire table.
You should ALWAYS name your form controls properly. If I sent you back to this code in a year's time and told you there was a problem with TextBox44, would you know what it means? Same goes for your variables. Sometimes it's ok to have i, x or tbl for a variable name, but in general they should be descriptive.
Example for #2, where I've put "'1/1/1999' WHERE 1=1 --" into TextBox45:
`UPDATE HireItemRecord SET HireItemBeginDate = '1/1/1999' WHERE 1=1 -- , HireItemEndDate...`
Everything after the -- becomes a comment, so you get this:
`UPDATE HireItemRecord SET HireItemBeginDate = '1/1/1999' WHERE 1=1`
Can you imagine what would happen if I executed that query? Nothing good.
You should use parameterized queries, as per the recommendations in this question: Algorithm to avoid SQL injection on MSSQL Server from C# code?
You should never use string concatenation to build SQL. It leaves you open to SQL Injection attacks. Try using the SQLCommand object provided in .Net. This allows you to "parameterize" your query and you don't have to worry about where to put " and '.
It will also allow you add parameters naturally without having to convert them to strings. Something like this:
Dim command As New SqlCommand("SELECT * FROM Table", connection)
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
I stole that code from the documentation about SQL Parameters here.