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

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 :)

Related

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

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)

Registering New Users in Database

I´m trying to insert new users in my database, but every time the register button is pressed i get an error message saying:
Syntax error in INSERT INTO statement.
My Code:
Private Sub cmdReg_Click()
Dim sql As String
Dim recordCount As Long
Dim rst As Long
Dim conn As ADODB.Connection
sql = "insert into LoginPasswords (Teacher_LName, Teacher_FName, PassWord, UserName) values ('" & txtLast.Text & "','" & txtFirst.Text & "','" & txtPass.Text & "','" & txtUser.Text & "')"
If CurrentCon.State = adStateOpen Then
CurrentCon.Close
End If
CurrentCon.Open
CurrentCon.Execute sql
End Sub
How do i fix this.
Your insert statement will depend on the column data types of your database.
But lets just say, for example, that you have all text fields in your database. Then you need to do is remove the quotes you have around each of the values.
Something like this:
Set MySet = MyConn.Execute("INSERT INTO Table_Name (col1, col2, col3) VALUES (txtcol1.text,txtcol2.text,txtcol3.text)");
Try to remove the extra quotes from your query.
If there are any integer values, change your insert statement like:
INSERT INTO Table_Name VALUES(CInt(txtcol1.text),txtcol2.text,txtcol3.text);

Exception Occur in VB.NET code

I was doing VB.NET and use it to connect my SQL database.
Right now I want to insert the data into my database, yet after I finish my code it comes out this error:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
What does it means and what do I do wrong in my code?
Here is my code:
Imports System.Data.SqlClient
Public Class AddNew
Public con As New SqlConnection("Data Source=localhost;Initial Catalog=Tuition_Information;Integrated Security=True")
Public cmd As New Data.SqlClient.SqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into Student_Info Value ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & ComboBox1.SelectedValue & "','" & ComboBox2.SelectedValue & "','" & TextBox7.Text & "','" & TextBox8.Text & "')"
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
MsgBox("New Student Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show("Error occured, please try again.")
End Try
End Sub
My Form looks like this:
My Database looks like this:
You're going to blow things up if you go about it the way you've got listed. What you need to do is to parameterize the query in some fashion - easiest way would be to create a stored procedure with named parameters. I say this will blow up because you do not account for the case wherein someone's name contains an apostrophe (and you can't tell me you won't have an O'Shannon or something), nor do you account for when a student is already registered. Something about that student must make them unique - like, maybe, Social Security Number? Which I assume you'll have during registration?
At that point, you could do something like:
create procedure SaveStudent
#Student_Name nvarchar(128) ,
#Home_Address nvarchar(256) ,
#Contact_Number varchar(32) ,
#Social_Security_Number char(11)
...
as
set nocount on
set rowcount 0
if exists ( select * from dbo.Students where Social_Security_Number = #Social_Security_Number )
begin
raiserror('Student with SSN %s already exists.', 16, 1, #Social_Security_Number) with nowait
end
else
begin
insert into dbo.Students (
Student_Name ,
Home_Address ,
Contact_Number ,
Social_Security_Number ,
... )
select
#Student_Name ,
#Home_Address ,
#Contact_Number ,
#Social_Security_Number ,
...
end
go
grant execute on SaveStudent to WhateverApplicationUserYouAreUsing
With that stored procedure in place, you'd then be able to bind those parameters, and you wouldn't be vulnerable to someone maliciously entering data, nor would you fall over when you get the first name with an apostrophe in it.
Obviously, you'd have to then bind to the stored procedure, which would mean preparing parameters & setting their values. But you'd be in better shape, and not vulnerable to the Little Bobby Tables problem.

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!

how to check duplicate record before insert, using vb.net and sql?

can someone help me with my code, i need to check first if record exist. Well i actually passed that one, but when it comes to inserting new record. im getting the error "There is already an open DataReader associated with this Command which must be closed first." can some help me with this? thanks.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim reg_con As SqlConnection
Dim reg_cmd, chk_cmd As SqlCommand
Dim checker As SqlDataReader
Dim ID As Integer
Dim fname_, mname_, lname_, gender_, emailadd_, college_, password_ As String
ID = idnumber.Value
fname_ = fname.Value.ToString
mname_ = mname.Value.ToString
lname_ = lname.Value.ToString
gender_ = gender.Value.ToString
college_ = college.Value.ToString
emailadd_ = emailadd.Value.ToString
password_ = reg_password.Value.ToString
reg_con = New SqlConnection("Data Source=JOSH_FLYHEIGHT;Initial Catalog=QceandCceEvaluationSystemDatabase;Integrated Security=True")
reg_con.Open()
chk_cmd = New SqlCommand("SELECT IDnumber FROM UsersInfo WHERE IDnumber = '" & ID & "'", reg_con)
checker = chk_cmd.ExecuteReader(CommandBehavior.CloseConnection)
If checker.HasRows Then
MsgBox("Useralreadyexist")
Else
reg_cmd = New SqlCommand("INSERT INTO UsersInfo([IDnumber], [Fname], [Mname], [Lname], [Gender], [Emailadd], [College], [Password]) VALUES ('" & ID & "', '" & fname_ & "', '" & mname_ & "', '" & lname_ & "', '" & gender_ & "', '" & emailadd_ & "', '" & college_ & "', '" & password_ & "')", reg_con)
reg_cmd.ExecuteNonQuery()
End If
reg_con.Close()
End Sub
Add this string to your connection string
...MultipleActiveResultSets=True;";
Starting from Sql Server version 2005, this string allows an application to maintain multiple active statements on a single connection. Without it, until you close the SqlDataReader you cannot emit another command on the same connection used by the reader.
Apart from that, you insert statement is very dangerous because you use string concatenation. This is a well known code weakness that could result in an easy Sql Injection vulnerability
You should use a parameterized query (both for the insert and for the record check)
reg_cmd = New SqlCommand("INSERT INTO UsersInfo([IDnumber], ......) VALUES (" & _
"#id, ......)", reg_con)
reg_cmd.Parameters.AddWithValue("#id", ID)
.... add the other parameters required by the other field to insert.....
reg_cmd.ExecuteNonQuery()
In a parameterized query, you don't attach the user input to your sql command. Instead you put placeholders where the value should be placed (#id), then, before executing the query, you add, one by one, the parameters with the same name of the placeholder and its corresponding value.
You need to close your reader using checker.Close() as soon as you're done using it.
Quick and dirty solution - issue checker.Close() as a first command of both IF and ELSE block.
But (better) you don't need a full blown data reader to check for record existence. Instead you can do something like this:
chk_cmd = New SqlCommand("SELECT TOP (1) 1 FROM UsersInfo WHERE IDnumber = '" & ID & "'", reg_con)
Dim iExist as Integer = chk_cmd.ExecuteScalar()
If iExist = 1 Then
....
This approach uses ExecuteScalar method that returns a single value and doesn't tie the connection.
Side note: Instead of adding parameters like you do now - directly to the SQL String, a much better (and safer) approach is to use parametrized queries. Using this approach can save you a lot of pain in the future.