vb.net Inserting data to access database - sql

I have the following code to input data into my Access database, but I am getting the following error.
Query input must contain at least one table or query.
What am I doing wrong? Here is the section of code that they is mentioning the lines.
Private Sub EditAddButton_Click(sender As Object, e As EventArgs) Handles EditAddButton.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*******************;Jet OLEDB:Database Password=************;")
Dim insertsql As String
Try
insertsql = "INSERT INTO RepairOrders" & _
"(ROOtherInfo, ROJobType, ROJobTime, RODelPicDate, RONo)" & _
"VALUES (#other, #type, #time, #delpic, #jobno) WHERE ROJobNo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have replaced certain information with asterixs' to cover some sensitive information.
EDIT:
Now I am getting a syntax error :(
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*********************************;Jet OLEDB:Database Password=***********;")
Dim insertsql As String
Try
insertsql = "UPDATE RepairOrders SET ROOther = #other, SET RONo = #jobno, SET ROJobType = #type, SET ROJobTime = #time, SET RODelPicDate = #delpic WHERE RONo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

It looks like you have too many SET statements, and OleDb requires '?' for parameters, and you must take care about the amount of them, and the order they are specified. This is a bit cleaned up, take a look at OLEDB Parameterized Query for a more thorough example.
Try
insertsql = "UPDATE RepairOrders
SET ROOther = ?
, RONo = ?
, ROJobType = ?
, SET ROJobTime = ?
, SET RODelPicDate = ?
WHERE RONo = ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("?", AddOtherText.Text)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
cmd.Parameters.AddWithValue("?", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("?", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("?", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

Related

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

transaction in ms access and vb.net

I am trying the below code but not getting executed.
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
cmd.Transaction = tra
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment) values('" + txtcategory.Text + "','" + txtcomment.Text + "')"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 WHERE (cname = txtcategory.Text)"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
Try : tra.Rollback() : Catch : End Try
End Try
End Using
End Sub
I don't understand the transactions.
The command need to know about the existence of a Transaction. But you assign the Transaction instance before the opening the connection and then ask the connection to start the transaction.
In this way the command has a null reference for the transaction and not the good instance created by the connection. Also, when you create again the command, there is no transaction associated with it.
Better use the OleDbCommand constructor that takes a Transaction as third parameter
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment)" &
" values(#cat, #com)"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#cat", OleDbType.VarWChar).Value = txtcategory.Text
cmd.Parameters.Add("#com", OleDbType.VarWChar).Value = txtcomment.Text
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 " &
"WHERE cname = #cat"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#car", OleDbType.VarWChar).Value = txtcategory.Text
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
tra.Rollback()
End Try
End Using
End
I have also changed your code to use a more safe approach to your queries. Instead of using a string concatenation use ALWAYS a parameterized query. In this way you are safe from Sql Injection, you don't have problems with parsing texts and your queries are more readable.

error 'There is already an open DataReader associated with this Command which must be closed first.'

I use below code but it gives error on sentence icount = cmd.ExecuteNonQuery
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Try always calling the Close method when you have finished using the DataReader object.
dr1.Close();
Another optionis to turn on MARS , in your connection string just add "MultipleActiveResultSets=True;"
Try this:
Try
insert data in combobox
cmd.Connection = con
cmd.CommandText = "select name from party"
dr = cmd.ExecuteReader()
cb_ms.Items.Add("---Select---")
cb_ms.SelectedIndex = 0
While dr.Read() 'get error here.'
cb_ms.Items.Add(dr("name"))
End While
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You could just close the datareader before the 2nd query, but it's better still to get this all into a single query in the first place. Moreover, you really need to close that awful sql injection issue.
Try this to fix both issues:
Dim sql As String = _
"IF NOT EXISTS
(
SELECT 1 FROM [SchoolERP].[dbo].[caste] where (caste = #caste )
)
BEGIN
INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES( #caste)
END"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Use actual columnn type from the database here
cmd.Parameters.Add("#caste", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cn.Open()
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
End Using
Use Try.. Catch.. Finally... End Try somehing like this:
Try
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Catch error As Exception
........
Finally
dr1.Close
End Try
I got Answer ... i only close connection before icount = cmd.ExecuteNonQuery this sentence and again open connection...and its works..
thanks disha..

VB.NET: SQL Parameters (Update)

I'm trying to update some values but it seems that there is a problem with my code.
Dim con As New OleDbConnection
Dim id As Integer = Main.Passes.Items.Count + 1
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ...\database.mdb"
con.Open()
Catch ex As Exception
MsgBox("There was a problem connection to database.", MsgBoxStyle.Critical)
End Try
Dim objCmd As OleDbCommand
Dim strSQL As String
strSQL = "UPDATE passwords SET website= #website, username= #username, password= #password, dates= #datenow, notes= #notes WHERE id= #id"
objCmd = New System.Data.OleDb.OleDbCommand(strSQL, con)
objCmd.Parameters.AddWithValue("#website", txtURL.Text)
objCmd.Parameters.AddWithValue("#username", txtUser.Text)
objCmd.Parameters.AddWithValue("#password", txtPass.Text)
objCmd.Parameters.AddWithValue("#datenow", txtDate.Text)
objCmd.Parameters.AddWithValue("#notes", txtNotes.Text)
objCmd.Parameters.AddWithValue("#id", id)
objCmd.ExecuteNonQuery()
con.Close()
The error I get is: Syntax error in UPDATE statement.
Try enclose your column names in `` (backticks). I guess password column is the culprit, probably a keyword.

SQL Update with where clause with variables from VS2010 Winforms

I am trying to do an update query from a winform with two variables without using a dataset.
I assign both of my variable and then run the query but it keeps giving the error that zcomp is not a valid column name. Which of course is true but I tell it which column before I say = zcomp. Below is my code that is running the query.
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - zamnt WHERE [ComponentID] = zcomp"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
I have tried it several different ways. It works just fine if I take out the zamnt and zcomp and put the actual number values that are in the variables. Please help I've been searching all day for a way to use the variables with this update query.
Thanks,
Stacy
You are probably looking for how to use parameters in ADO.NET. For your example, it can look like this:
cmd.Parameters.Add("#zamnt", zamnt);
cmd.Parameters.Add("#zcomp", zcomp);
Put these two lines anywhere before ExecuteNonQuery.
Because parameters need a # prefix, you would also need to change your query to say #zamnt instead of just zamnt, and same for zcomp:
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
In addition to using parameters, the "Using" statement closes the connection and disposes resources:
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Try
Using con As New SqlConnection("Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True")
con.Open()
Using cmd As New SqlCommand
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
cmd.Parameters.AddWithValue("#zamt", zamnt)
cmd.Parameters.AddWithValue("#zcomp", zcomp)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
have u tried this?
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] -" + zamnt + " WHERE [ComponentID] =" + zcomp
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try