VB.NET: SQL Parameters (Update) - sql

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.

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

vb.net Inserting data to access database

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

ORA-01036: illegal variable name/number - Insert Query

I am getting the ORA-01036: illegal variable name/number error in my vb.net application
Please take a look and help me.
Thanks in advance.
Dim sSQL As String
sSQL = "INSERT INTO PSLSC_PSL_NOMINATION ( NOMINATION_ID, NOM_TYPE, PROPOSED_STATUS, COMMODITY_TEAM, COMMODITY_DESC, COMMODITY_CODE, PARENT_ID, SUPPLIER_ID, SUPPLIER_NAME, ADDRESS, COUNTRY, TELEPHONE, CONTACT, WEBSITE, EMAIL, SPEND, TECHSOURCE_SCORE, ESAC_SCORE, PAYMENT_TERMS, MSA_CONTRACT, BUSA_CONTRACT, LEAN_CHAMPION, LEAN_CHAMPION_NAME, QUALITY, ON_TIME_DELIVERY, SUPPORTS_ESOURCING, COMPLIANCE_REQUIREMENT, FLEXIBILITY, CAP_MEET_DELIVERY_FREQ, NOMINATING_BUSINESS_UNIT, NOMINATING_REGION, OWNER, NOMINATED_DATE, COMMENTS, SENDER, SENDER_EMAIL )"
sSQL = sSQL & " VALUES ( :NOMINATION_ID,:NOM_TYPE,:PROPOSED_STATUS,:COMMODITY_TEAM,:COMMODITY_DESC,:COMMODITY_CODE,:PARENT_ID,:SUPPLIER_ID,:SUPPLIER_NAME,:ADDRESS,:COUNTRY,:TELEPHONE,:CONTACT,:WEBSITE,:EMAIL,:SPEND,:TECHSOURCE_SCORE,:ESAC_SCORE,:PAYMENT_TERMS,:MSA_CONTRACT,:BUSA_CONTRACT,:LEAN_CHAMPION,:LEAN_CHAMPION_NAME,:QUALITY,:ON_TIME_DELIVERY,:SUPPORTS_ESOURCING,:COMPLIANCE_REQUIREMENT,:FLEXIBILITY,:CAP_MEET_DELIVERY_FREQ,:NOMINATING_BUSINESS_UNIT,:NOMINATING_REGION,:OWNER,:NOMINATED_DATE,:COMMENTS,:SENDER,:SENDER_EMAIL )"
Dim obj_id As Decimal
obj_id = getNewSRM_OBJ_ID(cn_SRM)
Dim cn As OracleConnection = New OracleConnection(cn_proc)
Dim cmd As OracleCommand = New OracleCommand(sSQL, cn)
cmd.Parameters.Add(":NOMINATION_ID", obj_id)
cmd.Parameters.Add(":NOM_TYPE", row.NOM_TYPE)
cmd.Parameters.Add(":PROPOSED_STATUS", row.PROPOSED_STATUS)
cmd.Parameters.Add(":COMMODITY_TEAM", row.COMMODITY_TEAM)
cmd.Parameters.Add(":COMMODITY_DESC", row.COMMODITY_DESC)
cmd.Parameters.Add(":COMMODITY_CODE", row.COMMODITY_CODE)
cmd.Parameters.Add(":PARENT_ID", row.PARENT_ID)
cmd.Parameters.Add(":SUPPLIER_ID", row.SUPPLIER_ID)
cmd.Parameters.Add(":SUPPLIER_NAME", row.SUPPLIER_NAME)
cmd.Parameters.Add(":ADDRESS", row.ADDRESS)
cmd.Parameters.Add(":COUNTRY", row.COUNTRY)
cmd.Parameters.Add(":PHONE", row.PHONE)
cmd.Parameters.Add(":CONTACT", row.CONTACT)
cmd.Parameters.Add(":WEBSITE", row.WEBSITE)
cmd.Parameters.Add(":EMAIL", row.EMAIL)
cmd.Parameters.Add(":SPEND", row.SPEND)
cmd.Parameters.Add(":TECHSOURCE_SCORE", row.TECHSOURCE_SCORE)
cmd.Parameters.Add(":ESAC_SCORE", row.ESAC_SCORE)
cmd.Parameters.Add(":PAYMENT_TERMS", row.PAYMENT_TERMS)
cmd.Parameters.Add(":MSA_CONTRACT", row.MSA_CONTRACT)
cmd.Parameters.Add(":BUSA_CONTRACT", row.BUSA_CONTRACT)
cmd.Parameters.Add(":LEAN_CHAMPION", row.LEAN_CHAMPION)
If Not row.IsLEAN_CHAMPION_NAMENull Then
cmd.Parameters.Add(":LEAN_CHAMPION_NAME", row.LEAN_CHAMPION_NAME)
Else
cmd.Parameters.Add(":LEAN_CHAMPION_NAME", System.DBNull.Value)
End If
cmd.Parameters.Add(":QUALITY", row.QUALITY)
cmd.Parameters.Add(":ON_TIME_DELIVERY", row.ON_TIME_DELIVERY)
cmd.Parameters.Add(":SUPPORTS_ESOURCING", row.SUPPORTS_ESOURCING)
cmd.Parameters.Add(":COMPLIANCE_REQUIREMENT", row.COMPLIANCE_REQUIREMENT)
cmd.Parameters.Add(":FLEXIBILITY", row.FLEXIBILITY)
cmd.Parameters.Add(":CAP_MEET_DELIVERY_FREQ", row.CAP_MEET_DELIVERY_FREQ)
cmd.Parameters.Add(":NOMINATING_BUSINESS_UNIT", row.NOMINATING_BUSINESS_UNIT)
cmd.Parameters.Add(":NOMINATING_REGION", row.NOMINATING_REGION)
cmd.Parameters.Add(":OWNER", row.OWNER)
cmd.Parameters.Add(":NOMINATED_DATE", row.NOMINATED_DATE)
cmd.Parameters.Add(":COMMENTS", row.COMMENTS)
cmd.Parameters.Add(":SENDER", row.SENDER)
cmd.Parameters.Add(":SENDER_EMAIL", row.SENDER_EMAIL)
Try
cn.Open()
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
LOG_ERROR(ex.Message, sSQL, cn.ConnectionString, ex.Source)
End Try
You can also get this error when you omit the bind variable reference from the SQL but you create a Parameter for it. Ask me how I know this.
Example taken from above that might repro it (notice "PROPOSED_STATUS" is not in the SQL but is being added as Parameter:
sSQL = "INSERT INTO PSLSC_PSL_NOMINATION ( NOMINATION_ID, NOM_TYPE ) VALUES ( :NOMINATION_ID,:NOM_TYPE )"
Dim obj_id As Decimal = getNewSRM_OBJ_ID(cn_SRM)
Dim cn As OracleConnection = New OracleConnection(cn_proc)
Dim cmd As OracleCommand = New OracleCommand(sSQL, cn)
cmd.Parameters.Add(":NOMINATION_ID", obj_id)
cmd.Parameters.Add(":NOM_TYPE", row.NOM_TYPE)
cmd.Parameters.Add(":PROPOSED_STATUS", row.PROPOSED_STATUS)
Try
cn.Open()
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
LOG_ERROR(ex.Message, sSQL, cn.ConnectionString, ex.Source)
End Try

Sql Adapter . How to update a DataTable with no primary keys

This table that I have has been created with no primary keys. There is a reason why its been created with no keys. It is something like a product and customer relationship table. So after the standard procedure of using SqlDataAdapter and DataSet along with DataTable to fill the DataGrid I have an error updating the changes.
I have been working on several forms using DataGrid' but they all work fine due to the fact the table have primary keys. I tried adding a composite key but it didn't work. So below is my code for theDataSet` and the update code which works for other forms.
The update codes:
cmdbuilder = New SqlCommandBuilder(adapter)
If primaryDS IsNot Nothing Then
primaryDS.GetChanges()
'update changes
adapter.Update(primaryDS)
MsgBox("Changes Done")
'refresh the grid
CMDrefresh()
End If
And here is the coding for the DataTable I tried adding 5 composite keys. So how do you update with this problem?
Try
myconnection = New SqlConnection(strConnection)
myconnection.Open()
adapter = New SqlDataAdapter(StrQuery, myconnection)
adoPrimaryRS = New DataSet
adapter.Fill(primaryDS)
Dim mainTable As DataTable = primaryDS.Tables(0)
DataGrid.AutoGenerateColumns = False
mainTable.PrimaryKey = New DataColumn() {mainTable.Columns(0), _
mainTable.Columns(1), _
mainTable.Columns(2), _
mainTable.Columns(3), _
mainTable.Columns(4)}
bndSrc.DataSource = mainTable
DataGrid.DataSource = bndSrc
gDB.Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
So I decided to go on and answer my question. You cant use the code above to up but you can still insert the new rows. Since Dataset is a memory if the whole database was removed it would not be effect. So the answer to how to update a table with no primary key or composite keys it to trancute it then insert all rows from the Dataset Table in to it. Here is the Code for Trancute and The one below is to insert. With these the table gets new values. It works for me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = strConnection
Dim strSql As String
'MsgBox(con.ConnectionString.ToString)
Try
con.Open()
cmd = New SqlCommand
cmd.Connection = con
strSql = "TRUNCATE TABLE Table1"
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So here is The Insert code.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim strSql As String
con.ConnectionString = strConnection
For i As Integer = 0 To grdDataGrid.Rows.Count - 1
'MsgBox(con.ConnectionString.ToString)
con.Open()
cmd = New SqlCommand
cmd.Connection = con
Try
strSql = "INSERT INTO Table1 ( [one], [two], [three], [four], [five] )" +_
"VALUES (#one, #two, #three ,#four ,#five )"
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("#one", grdDataGrid.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#two", grdDataGrid.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("#three", grdDataGrid.Rows(i).Cells(1).Value)
cmd.Parameters.AddWithValue("#four", grdDataGrid.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#five", grdDataGrid.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
CMDrefresh()

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