Vb.Net 2010 - SQL Insert Command with autonumeric value - sql

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

Related

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with

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..

How to update multiple data to Database?

Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc

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