VB 2010 Express connected to database microsoft access 2010 - vb.net-2010

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim sqlquery As String = "INSERT INTO Table1(Customer Name,Address,Contact Number,Type Of Customer)VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "')"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("ONE RECORD SUCCESFULLY ADDED :)")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can somebody help me? It says that there is an error in INSERT INTO statement, i dont know why. Thanks for the help.

Try putting [] around column names that contain a space.
( [Customer Name], Address, [Contact Number], [Type Of Customer] )

It is important to enclose your field in [your field] when they have spaces in them, else it considers it as two fields and search for separator which there is none in this case.
hopes my answers helps a little.

Related

"Data type mismatch in criteria expression" error when updating a table

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=..\VisitorPass.accdb"
Dim sql As String
sql = "Update Visitor set [password]='" & txtPassword.Text & "',FirstName='" & txtFirstName.Text & "',LastName='" & txtLastName.Text & "',Gender='" & txtGender.Text & "',MobileNo='" & txtMobileNO.Text & "',DateOfBirth='" & txtDateOfBirth.Text & "',VisitorAddress='" & txtVisitorAddress.Text & "'where ID='" & lblID2.Text & "'"
con = New OleDbConnection(str)
Dim cmd As New OleDbCommand(sql, con)
con.Open()
cmd.ExecuteNonQuery()
Dim obj1 As New VisitorProfile
obj1.StringPass = txtName.Text
MsgBox("profile is updated")
obj1.Show()
con.Close()
Me.Close()
End Sub
There is only one field in your criteria expression, Id. I'd suspect instead of being Text it's actually an Integer. So remove the quotes: (also add in a space between the single quote and where).
"' where ID=" & lblID2.Text & "
However this leaves you open to an sql injection attack so you should parameterize your query.

Database Application Connection Errors

I keep getting a "Connection was not established" error. Though I thought, what with opening the Connection with sqlLink.Open and sqlCheck.connection = sqlLink, that this error wouldn't appear.
Imports System.Data.OleDb
Public Class StockAdd
Dim path = System.Windows.Forms.Application.StartupPath
Dim sqlLink As OleDbConnection
Private Sub StockAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sqlLink = New OleDbConnection
sqlLink.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\will\Documents\Computing\ComputingProjectDatabase.accdb';")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlCheck As New OleDbCommand
Dim oleRdr As OleDbDataReader
sqlLink.Open()
Try
Using sqlOrder As New OleDbCommand
sqlCheck.Connection = sqlLink
sqlCheck.CommandText = "SELECT count(*) FROM StockSystem WHERE [Stock ID] = #stockID"
sqlCheck.Parameters.AddWithValue("#stockID", TextBox5.Text)
oleRdr = sqlCheck.ExecuteReader()
If oleRdr.HasRows = True Then
oleRdr.Read()
If oleRdr.Item(0) = 0 Then
sqlOrder.CommandText = "INSERT INTO StockSystem ([Stock ID], [Stock Price], [Stock Size], [Stock Quantity], [Stock Category]) VALUES ('" & TextBox5.Text & "','" & TextBox7.Text & "','" & TextBox6.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "')"
sqlOrder.ExecuteNonQuery()
MsgBox("Stock Details Stored.")
Else
MsgBox("Please check you have entered the correct data.")
End If
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
sqlLink.Close()
Me.Close()
Stock.Show()
End Sub
End class
If my eyes don't fail me, you don't set the connection for the sqlOrder command. So it cannot execute your sql text.
Pay attention, you cannot use the sqlLink connection because it is used by the datareader. You need a new connection object (with the same connection string of course)
As a side note, your code is very vulnerable to Sql Injection. And probably could have serious problems if one or more of your TextBoxes contains a single quote char.
Always use a parameterized query as the one used for the COUNT() statement before

vb.net 2008 insertion command for ms access is not showing any error but not inserted into table

I written some code to insert data of form into ms access database
it runs successfully and gives no error
but when I see in data base I found there is no data inserted in the database.
what is the problem?
So guys, please help me.
Here is my vb.net code :
Private Sub btnCreateUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateUser.Click
Dim con2 As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OfficeAutomationSystem.accdb; Persist Security Info=False")
Dim cmd As New OleDb.OleDbCommand
If Not con2.State = ConnectionState.Open Then
con2.Open()
End If
cmd.Connection = con2
'add data to table
cmd.CommandText = "INSERT INTO tblUser(emp_id, user_id, pwd, user_type) " & _
" values(" & Me.cbEmpId.SelectedItem & ", '" & Me.txtUserId.Text & "','" & _
Me.txtPassword.Text & "', '" & Me.cbUserType.SelectedItem & "')"
cmd.ExecuteNonQuery()
MsgBox("running")
End Sub
and here is my data base structure of ms access database :
field name dataYpe
serial_no AutoNumber
emp_id Number
user_id Text
pwd Text
user_type Text
Thanks in advance .
Can you try to execute this code and just let me know if it works
Private Sub btnCreateUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateUser.Click
Dim con2 As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OfficeAutomationSystem.accdb; Persist Security Info=False")
Dim cmd As New OleDb.OleDbCommand
If Not con2.State = ConnectionState.Open Then
con2.Open()
End If
cmd.Connection = con2
'add data to table
cmd.CommandText = "INSERT INTO tblUser(emp_id, user_id, pwd, user_type) " & _
" values(" & Convert.ToInt32(Me.cbEmpId.SelectedItem) & ", '" & Me.txtUserId.Text & "','" & _
Me.txtPassword.Text & "', '" & Me.cbUserType.SelectedItem & "')"
cmd.ExecuteNonQuery()
MsgBox("running")
End Sub

Syntax error in UPDATE statement access database in vb.net

I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.

Syntax Error in Insert Statement

I'm new to Database connection and when I am having a problem with the cmdInsert.ExecuteNonQuery() line it says there is a syntax error with the INSERT INTO statement and I can't figure out what the problem is:
Imports System.Data
Imports System.Data.OleDb
Public Class txtNotes
Dim cnnOLEDB As New OleDbConnection
Dim cmdInsert As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\CourseworkDB"
'the name of the database goes in here'
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
End Sub
Private Sub AddFirstName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFirstName.Click
If txtFirstName.Text <> "" Then
MsgBox(cmdInsert.CommandText)
cmdInsert.CommandText = "INSERT INTO Customer (First Name) VALUES (" & txtFirstName.Text & ", '"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
Else
MsgBox("Enter the required values:" & vbNewLine & "1. First Name")
End If
cmdInsert.Dispose()
End Sub
End Class
I Strongly suggest not getting into a routine of building SQL strings by concatinating strings together. You are leaving yourself wide open to SQL-Injection, especially if this is web based. You should build your commands with place-holder parameters in the string, then add the parameters to the command object. Add the parameters in the same sequence as they would appear in the command... such as
cmdInsert.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES ( #parmFirstName, #parmLastName )"
cmdInsert.Parameters.AddWithValue( "#parmFirstName", txtFirstName.Text );
cmdInsert.Parameters.AddWithValue( "#parmLastName", txtLastName.Text );
If your field names have embedded spaces, different databases work
differently, some requires single backtick (the key left of the number
1) around the field. such as 'first name'. Some use square brackets,
such as [first name].
Try this
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"
Warning: Bobby is watching you.
cmdInsert.CommandText = _
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"