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
Related
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
I have those three text boxes by the name StandardPath_TextBoxA1, StandardPath_TextBoxA2, StandardPath_TextBoxA3 and through a FOR loop I am trying to save their text values into an ms access database file. I am trying something like this below, but my syntax is wrong... Any idea?
For i = 1 To 3
Dim str(i) As String
str(i) = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str(i), MyConnection)
cmd.Parameters.Add(New OleDbParameter("TagNum", CType("A" & i, String)))
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
EDIT:
The syntax error located here:
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))
Try this. It fixes some type-mismatches in the original, as well as removing unnecessary variables and redundancy.
Dim sql As String = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
'DON'T RE-USE YOUR DATABASE CONNECTION, EXCEPT FOR SHORT BURSTS IN TIGHT LOOPS LIKE THIS
Using connection As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand(sql, connection)
'Guessing at column types and lengths. Use actual types from your database here
cmd.Parameters.Add("TagNum", OleDbType.VarChar, 2)
cmd.Parameters.Add("Title", OleDbType.VarWChar, 100)
cmd.Parameters.Add("Path", OleDbType.VarWChar, 512)
'Do this just once, outside the loop, to avoid needing to repeatedly re-negotiate with the DB. Let the USING black take care of closing the connection
connection.Open()
For i = 1 To 3
Dim TitleLabel As Control = Me.Controls.Find("StandardPath_LabelA" & i.ToString(), True).First()
Dim PathBox As Control = Me.Controls.Find("StandardPath_TextBoxA" & i.ToString(), True).First()
cmd.Parameters(0).Value = "A" & i.ToString()
cmd.Parameters(1).Value = TitleLabel.Text
cmd.Parameters(2).Value = PathBox.Text
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
End Using
Even better if you have already grouped these controls in related panel or similar control, or added them to an array. That could allow better options than Controls.Find(), but I saw no indication of this in the question.
One other option, since the number of items is small, is to do it like this:
Dim sql As String = _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);"
Using connection As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand(sql, connection)
'Guessing at column types and lengths. Use actual types from your database here
cmd.Parameters.Add("TagNum1", OleDbType.VarChar, 2).Value = "A1"
cmd.Parameters.Add("Title1", OleDbType.VarWChar, 100).Value = StandardPath_LabelA1.Text
cmd.Parameters.Add("Path1", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA1.Text
cmd.Parameters.Add("TagNum2", OleDbType.VarChar, 2).Value = "A2"
cmd.Parameters.Add("Title2", OleDbType.VarWChar, 100).Value = StandardPath_LabelA2.Text
cmd.Parameters.Add("Path2", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA2.Text
cmd.Parameters.Add("TagNum3", OleDbType.VarChar, 2).Value = "A3"
cmd.Parameters.Add("Title3", OleDbType.VarWChar, 100).Value = StandardPath_LabelA3.Text
cmd.Parameters.Add("Path3", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA3.Text
connection.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
I know the repeated code is often seen as bad, but for three items sometimes a loop is just overkill. In this case, skipping the loop also gives an advantage of reducing you to a single atomic trip to the 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.
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.
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.