Insert multiple rows in access database using oledb parameters - sql

I am trying to insert multiple rows in a listitems to a database using parameters.
But it won't give me any errors, and also won't insert any data in the table.
does anyone have any ideas on this one?
strSQL = "insert into tbltrans2 (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtTransId.Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
Next ls
End Using
Hey steve, When I try that, it gives me 'syntax error in update statement' erro. Here is my code:
Try
strSQL = "UPDATE set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ls.Tag
cmd.ExecuteNonQuery()
Next ls
cn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now, I still need help with decreasing the stock. Here is the code that I use, but it isn't working.
strSQL = "UPDATE tblitem set instock ='instock'- ? where itemcode = ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In SalesListItems.Items
If Not (ls.SubItems(1).Tag(0) = "n") Then
cmd.Parameters.Add("?", OleDbType.Integer).Value = ls.SubItems(1).Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10).Value = ls.Tag
cmd.ExecuteNonQuery()
End If
Next ls
cn.Close()
End Using

You are missing the execute part
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
Also, are you certain on the input values coming from the subitems? If there isn't a control on their effective numeric value when you add them to the ListView, then the loop could fail with an exception when you try to convert the supposed numeric value with Parse.
EDIT: This instead for an update
strSQL = "UPDATE tblitem set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("......")
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = yourItemCodeValue
cmd.ExecuteNonQuery()
End Using
Keep in mind that I suppose instock is a integer data type and itemcode a varchar.

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 SQL Insert Statement seems to work but doesn't actually change Database

This is the code:
Dim insertSql As String = "INSERT INTO StudentTable(BadgeNo,FirstName,LastName,SAPID,Email,Phone,College) VALUES (?,?,?,?,?,?,?)"
Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\Users\larsennicholasg\Documents\Visual Studio 2012\Projects\SSCLogin\SSCLogin\My Project\SSCStudent.mdb"""
Using conn As New OleDbConnection(connStr), cmd As New OleDbCommand(insertSql, conn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = CInt(BadgeNoTextBox.Text)
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = FirstNameTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = LastNameTextBox.Text
cmd.Parameters.Add("?", OleDbType.Integer).Value = CInt(SAPSIDTextBox.Text)
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = EmailTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = PhoneTextBox.Text
cmd.Parameters.Add("?", OleDbType.WChar, 255).Value = CollegeComboBox.Text
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
It passes through the program fine (finally), however doesn't actually seem to update the database at all. Is there a save command, or a push command I'm missing?
What I'd like is it to take this information and insert it into the table, so if the program closes, it's still in the database.

Update an MS Access database in a loop with paramaters with vb.net

I was trying to update a field called 'instock'( type is double in database), where the itemcode is a value (type is long integer in access database). But when I try to update them, I get a error which says 'Invalid index 2 for this oledbparamterCollection with count=2. Can anyone help me please?
strSQL = "UPDATE tblitem set instock = ? where itemcode= ? "
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Double)
cmd.Parameters.Add("?", OleDbType.integer)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
If Not (ls.SubItems(1).Tag(0) = "n") Then
cmd.Parameters(1).Value = (ls.SubItems(1).Tag - ls.SubItems(1).Text)
cmd.Parameters(2).Value = ls.Tag
cmd.ExecuteNonQuery()
End If
Next ls
cn.Close()
End Using
Thanks , + I get this error 'no default member found for the type double' while exucating this command:
strSQL = "UPDATE tblitem set instock = ? where itemcode= ? "
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Double)
cmd.Parameters.Add("?", OleDbType.Double)
cn.Open()
For Each ls As ListViewItem In SalesListItems.Items
If Not (ls.SubItems(1).Tag(0) = "n") Then
cmd.Parameters(0).Value = (CDbl(ls.SubItems(1).Tag) + CDbl(ls.SubItems(1).Text))
cmd.Parameters(1).Value = Integer.Parse(ls.Tag)
cmd.ExecuteNonQuery()
End If
Next ls
cn.Close()
End Using
Indices are 0-based in the .NET class library, including ADO.NET1
Parameters(1) means "the 2nd parameter" and Parameters(2) means "the 3rd parameter" (which is invalid here).
1 This isn't true for all collections, but it is the most prevalent convention used these days. For instance, collections in the Outlook Object Model, which is COM exposed to .NET, indices are still 1-based ..

Update multiple rows in access database using oledb parameters

I am trying to update multiple rows in a access database using parameters. I already have to code to insert to a database, but I need same type of code to update the database.
My update string looks like this Update tblitem set instock='value' where itemcode='value2'
Here is my code to insert:
strSQL = "insert into tbltrans2 (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtTransId.Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
End Using
You should, at the most basic level, be able to modify your sql string to indicate parameter placeholders (?) as you did in your Insert query, eg
Update tblitem set instock=? where itemcode=?
The concept beyond that, eg creating/setting the parameters, is essentially the same. Hope I'm understanding your problem properly. Good luck.

Insert multiple lines of query in a sql database access

I was trying to insert items in a listview in a database. If I try to insert every records seperately, it takes long if there are more records (even more than 5).
Im currently using this code:
For Each ls As ListViewItem In ListItems.Items
strSQL = String.Format("insert into tbltrans (transid,itemcode,itemname,qty,price,[total],btw) values ('{0}','{1}','{2}',{3},{4},'{5}','{6}')", CStr(txtTransId.Text), CStr(ls.Tag), ls.SubItems(0).Text, CDbl(ls.SubItems(1).Text), CDbl(ls.SubItems(2).Text), CDbl(ls.SubItems(3).Text), ((ls.SubItems(5).Text)))
objDal.ExecuteQuery(strSQL)
Next
So, what I want to do is execute all of the items in one sql query.
I tried this, but didn't work:
strSQL = "insert into tbltrans (transid,itemcode,itemname,qty,price,[total],btw) values "
For Each ls As ListViewItem In ListItems.Items
strSQL += tring.Format("('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", CStr(txtTransId.Text), CStr(ls.Tag), ls.SubItems(0).Text, CDbl(ls.SubItems(1).Text), CDbl(ls.SubItems(2).Text), CDbl(ls.SubItems(3).Text), ((ls.SubItems(5).Text)))
Next
objdal.executequery(strSQL)
It says that it's missing semicolon(;) at the end of the statement, I tried adding them in the records and also (strsql & ";"), then it gives syntax error.
can anyone help please?
You can do a little better by re-using the same command/connection object and same (not re-constructed) sql string like this (I had to guess at column types and lengths):
strSQL = "insert into tbltrans (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Connection string here"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = Integer.Parse(txtTransId.Text)
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
End Using