Syntax error in INSERT INTO statement for register - sql

Dim con As New OleDb.OleDbConnection
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=..\VisitorPass.accdb"
con = New OleDbConnection(str)
Dim sql As String = "insert into Visitor(Name,Password)values ('" & txtName.Text & "','" & txtPassword.Text & "')"
Dim cmd As OleDbCommand
con.Open()
cmd = New OleDbCommand(sql, con)
cmd.ExecuteNonQuery()
MsgBox("Account is Registered")

Try enclosing the field password in brackets.
insert into Visitor(Name,[Password])values ..
This should do the trick when using MS Access.

Related

VB.net insert into error [duplicate]

This question already has an answer here:
Syntax error in INSERT INTO Statement when writing to Access
(1 answer)
Closed 7 years ago.
I'm using Microsoft Visual Studio 2013 and im trying to make a registration form for my account database using VB.NET. This is my code so far:
Private Sub btnRegistery_Click(sender As Object, e As EventArgs) Handles btnRegistery.Click
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(usernme , passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
End Sub
The code compiles fine, but when i try to register any new information i get the following message:
A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
What could be a solution and cause for this problem?
Your query seems wrong: ... VALUES(usernme, passwrd)... --
Here the usernmeand passwrd are not variables for database, but just plain text in the query.
Use parameters, like this:
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [tbl_user] ([username], [password]) VALUES (#usernme, #passwrd)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
End using
End using
You aren't including the actual variable information missing the quotations, like
VALUES ('" & usernme & '", ...etc
You should be using parameters to avoid errors and sql injection:
sqlQry = "INSERT INTO tbl_user (username, password) VALUES(#usernme, #passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'-------------open connection-----------
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select stdID as [StdIdTxt]," &
"Fname as [FnameTxt] ,Lname,BDy,age,gender,address,email,LNO,MNO,course" &
"from studentTB order by stdID", cnn)
Dim dt As New DataTable
'------------fill data to data table------------
da.Fill(dt)
'close connection
cnn.Close()
End Sub
Private Sub AddNewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewBtn.Click
Dim cmd As New OleDb.OleDbCommand
'--------------open connection if not yet open---------------
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'----------------add data to student table------------------
cmd.CommandText = "insert into studentTB (stdID,Fname,Lname,BDy,age,gender,address,email,LNO,MNO,course)" &
"values (" & Me.StdIdTxt.Text & "','" & Me.FnameTxt.Text & "','" & Me.LNameTxt.Text & "','" &
Me.BdyTxt.Text & "','" & Me.AgeTxt.Text & "','" & Me.GenderTxt.Text & "','" &
Me.AddTxt.Text & "','" & Me.EmailTxt.Text & "','" & Me.Hometxt.Text & "','" & Me.mobileTxt.Text & "','" & Me.Coursetxt.Text & "')"
cmd.ExecuteNonQuery()
'---------refresh data in list----------------
'RefreshData()
'-------------close connection---------------------
cnn.Close()
This insert error is nothing but a syntax error, there is no need for changing your code. please avoid reserved words like "password" form your database. This error is due to the field name password
The SQL string should look like this
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(" & usernme & "', " & passwrd & ")"
The values usernme & passwrd aren't valid to the database.
Beyond that you really should look into using a Command object and parameters.

VB.Net - ExecuteReader: CommandText property has not been initialized

I know there are some threads about this topic, but for some reason nothing of these things given there didn't work for me. So that is my code:
Dim strAccSQL As String = "SELECT nUserNo FROM dbo.tUser WHERE sUserID='" & AccountID.Text & "';"
Dim catCMDAcc As SqlCommand = New SqlCommand(strAccSQL, AccCon)
Dim myAccountReader As SqlDataReader = catCMDAcc.ExecuteReader()
While myAccountReader.Read
AccountNo.Text = myAccountReader(0)
End While
myAccountReader.Close()
Con.Close()
Con.Open()
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
InfoTextBox.Text &= Environment.NewLine & Now & " Account: " & AccountID.Text & " Found"
CharacterName.Properties.Items.Clear()
While myReader.Read()
CharacterName.Properties.Items.Add(myReader(0))
End While
myReader.Close()
AccCon.Close()
Con.Close()
Anyone got an idea for my problem?
As the errormessage states, your CommandText is empty string here (strSQL2):
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
You cannot execute an empty sql-clause.

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

VB.net 2010 dataset updates but access database remains same

I have tried to insert or update from my vb.net form into MS-Access database.
The dataset updates but the access database wont. Below is my code.
Try
Dim addLocation As String = "Insert into Provider (StateCode, Provider)" _
& "values ('" & ComboBox1.Text & "', '" & TextBox2.Text & "')"
Dim sqlcommand As New OleDbCommand
conn.Open()
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record added", MsgBoxStyle.Information)
refreshGrid()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Private Sub refreshGrid()
cnString = "PROVIDER = Microsoft.ace.oledb.12.0;data source =" & Application.StartupPath & "\HCHPClosedIn.accdb"
sqlQRY = "SELECT * FROM Provider"
conn = New OleDbConnection(cnString)
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Customers")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers"
End Try
End Sub
Its been a while but I think I recall Access is kinda picky with commit. Try this:
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
.transaction = trans
End With
Trans.Commit()

Insert new records into a table with Visual Basic using OLEDBConnection

I'm using Visual Basic 2010 Express and Access 2003.
I'm trying to make sql querys to the mdb file. I'm using OLEDBConnection. The Select query works fine, but I can't insert rows in the table. Here is the code.
Dim connStr As String = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & System.IO.Directory.GetCurrentDirectory() & "\tpv.mdb;"
Dim con As New OleDb.OleDbConnection(connStr)
con.Open()
Dim query As String = "select * from Productos"
Dim cmd As New OleDb.OleDbCommand(query, con)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader
While reader.Read()
MsgBox(reader.GetValue(0) & ", " & reader.GetValue(1) & " , " & reader.GetValue(2))
End While
reader.Close()
query = "insert into Productos (NombreProducto,PrecioCoste) VALUES ('cana',4)"
Dim cmd2 As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
Why the INSERT query does not work?
Ok, I found my stupid problem.
Althoug I have declared 2 OleDbCommands, I referenced the first one in both cases