Update multiple rows in access database using oledb parameters - sql

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.

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.

Insert multiple rows in access database using oledb parameters

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.

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

SQL Server CE query having no effect?

I'm attempting to insert rows into a SQL Server CE database, and it's returning that 1 row is affected, there's no exception, and no syntax error in the query as far as I can see - but it's having no effect, when I look in the table from the Database Explorer.
If I run a query through VS, everything works fine. There's no connection problem as far as I can tell... what am I doing wrong here?
Here's the code, though it probably doesn't make a difference:
Using conn As New SqlCeConnection(My.Settings.DietSafetyCheckerReportsConnectionString)
conn.Open()
Using cmd As SqlCeCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Reports(PatientID, PreparedBy, PreparedFor, WeightInKilos, HeightInMeters, Age, PercentBodyFat, ElbowMeasurementInCentimeters, ReportDate, Gender) " &
"VALUES(#pid, #pby, #pfor, #weight, #height, #age, #bodyfat, #elbow, #rdate, #gender);"
cmd.Parameters.Add("#pid", SqlDbType.NVarChar, 100).Value = Me.PatientID
cmd.Parameters.Add("#pby", SqlDbType.NVarChar, 100).Value = Me.PreparedBy
cmd.Parameters.Add("#pfor", SqlDbType.NVarChar, 100).Value = Me.PreparedFor
cmd.Parameters.Add("#weight", SqlDbType.Float).Value = Me.WeightInKilos
cmd.Parameters.Add("#height", SqlDbType.Float).Value = Me.HeightInMeters
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Me.Age
cmd.Parameters.Add("#bodyfat", SqlDbType.Float, 100).Value = Me.PercentBodyFat
cmd.Parameters.Add("#elbow", SqlDbType.TinyInt, 100).Value = Me.ElbowMeasurementInCentimeters
cmd.Parameters.Add("#rdate", SqlDbType.DateTime).Value = Me.ReportDate
cmd.Parameters.Add("#gender", SqlDbType.TinyInt, 100).Value = Me.Gender
If cmd.ExecuteNonQuery() <> 1 Then Throw New ApplicationException("Failed to insert row into databse.")
End Using
conn.Close()
End Using
(By the way, this also doesn't work:
Using da As New SqlCeDataAdapter("SELECT * FROM Reports", conn)
Dim ds As New DietSafetyCheckerReportsDataSet()
Dim dt As DietSafetyCheckerReportsDataSet.ReportsDataTable
da.Fill(ds)
dt = DirectCast(ds.Tables("Reports"), DietSafetyCheckerReportsDataSet.ReportsDataTable)
Dim dr As DietSafetyCheckerReportsDataSet.ReportsRow = dt.NewReportsRow()
dr.Age = Me.Age
dr.ElbowMeasurementInCentimeters = Me.ElbowMeasurementInCentimeters
dr.Gender = Me.Gender
dr.HeightInMeters = Me.HeightInMeters
dr.PatientID = Me.PatientID
dr.PercentBodyFat = Me.PercentBodyFat
dr.PreparedBy = Me.PreparedBy
dr.PreparedFor = Me.PreparedFor
dr.ReportDate = Me.ReportDate
dr.WeightInKilos = Me.WeightInKilos
dt.Rows.Add(dr)
da.Update(ds)
End Using
)
Look in your bin/debug folder, you probably have more copies of the same database file
My suggestion is that you turned off autocommit mode on server (which is on by default) or on connection settings, so you need to commit your transaction manually. Take a look here for more info.