VB.Net Update doesn't update my database - sql

This is the code that I am trying to run. It will run without errors, but it does not update my database.
It will work when it is not Parameterized, but when I add parameters in it starts acting up. Here is the problematic code.
Public Sub updateItem()
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
cmd.CommandText = "Update Inventory set PartNumber='#PartNumber', Brand='#Brand', PartDescription='#PartDescription', PartCost=#PartCost, InventoryOnHand=#InventoryOnHand, PartSupplier='#PartSupplier' where PartNumber = '#PartNumMatch' and Brand = '#PartManMatch';"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
'SQl statement to try to update the selected row's data matched against the database.
'update listview here.
End Sub
I am almost sure that the syntax is correct because my insert works. Here is the code to my insert.
Private Sub addItem()
'SQL statement here to add the item into the database, if successful, move the information entered to listview.
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
'Dim reader As SqlDataReader
cmd.CommandText = "Insert into Inventory ([PartNumber], [Brand], [PartDescription], [PartCost], [InventoryOnHand], [PartSupplier]) values (#PartNumber, #Brand, #PartDescription, #PartCost, #InventoryOnHand, #PartSupplier);"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text().Trim())
cmd.Parameters.AddWithValue("#PartCost", partCostText.Text())
cmd.Parameters.AddWithValue("#InventoryOnHand", quantityText.Text())
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Dim found As Boolean = False
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
MessageBox.Show(cmd.CommandText)
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
End Sub
I know that the where clause is right, I have hard-coded the value's and I have also pushed the value's being compared to message box's and compared them directly to the information in the database.
Thanks in advance for any and all opinions and I hope we can get it figured out.

The parameters placeholders should not be enclosed in single quotes
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
You don't need to do that, it only confuses the code that tries to replace the parameter placeholder with the actual value. They will be treated as literal strings

Try this,
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())

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

ASP.NET, VB.NET can't insert data into a SQL Server database

I have been troubleshooting this for a week. I try to insert a value into a SQL Server database. It doesn't show any error but when I check the database, there's no data inserted. I might doing something that is wrong here but I can't find it. Thanks for helping.
Dim connect As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlServer").ToString())
Using coa As New SqlCommand()
With coa
.Connection = connect
.CommandType = CommandType.Text
End With
Try
connect.Open()
Dim insertcmd As String
insertcmd = "insert into tblUserSection (#newValue, #SectionName, #newSectionID) values ," _
& "#newValue, #SectionName, #newSectionID);"
coa.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
coa.Parameters("#newValue").Value = newValue
coa.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
coa.Parameters("#SectionName").Value = SectionName.ToString
coa.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
coa.Parameters("#newSectionID").Value = newSectionID
coa.ExecuteNonQuery()
connect.Close()
MsgBox("success insert")
Catch ex As Exception
MsgBox("Fail to Save to database")
End Try
End Using
The insert command is incorrect. It has parameters for both the column names and the value; the parameter names should only be used for the values.
Assuming the column names match the parameter names, here's an updated version of the command.
insertcmd = "insert into tblUserSection (newValue, SectionName, newSectionID) values ," _
& "#newValue, #SectionName, #newSectionID);"
The more curious question is why isn't an error showing up. That's because the insert statement is never getting executed. The ExecuteNonQuery command is run against the connection but insertcmd is never associated with the execution in any way.
I'd recommend creating a SQLCommand and using that to execute the query. Here's a sample (and my code might have mistakes, my vb.net is pretty rusty):
Dim sqlcommand as New SqlCommand(coa)
sqlcommand.text = insertcmd
sqlcommand.type = Text
sqlcommand.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
sqlcommand.Parameters("#newValue").Value = newValue
sqlcommand.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
sqlcommand.Parameters("#SectionName").Value = SectionName.ToString
sqlcommand.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
sqlcommand.Parameters("#newSectionID").Value = newSectionID
sqlcommand.ExecuteNonQuery()
You need to set CommandText property of SqlCommand after creating the insert command string.
like:
Dim connect As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlServer").ToString())
Using coa As New SqlCommand()
With coa
.Connection = connect
.CommandType = CommandType.Text
End With
Try
connect.Open()
Dim insertcmd As String
insertcmd = "insert into [TableName] (newValue, SectionName, newSectionID) values " _
& "(#newValue, #SectionName, #newSectionID);"
coa.CommandText = insertcmd
coa.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
coa.Parameters("#newValue").Value = newValue
coa.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
coa.Parameters("#SectionName").Value = SectionName.ToString()
coa.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
coa.Parameters("#newSectionID").Value = newSectionID
coa.ExecuteNonQuery()
connect.Close()
MsgBox("success insert")
Catch ex As Exception
MsgBox("Fail to Save to database")
End Try
End Using

How to insert listview items into 3 different tables VB.net

I'm trying to make a library system. I have a listview and it contains items to be inserted into different tables, (b_borrow_tbl, for the books , d_borrow_tbl for the multimedia, and m_borrow_tbl for the module).
I'm using this code to insert items to b_borrow_tbl:
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
Here's one possibility. Note that I can't give you exact code because I don't know the structure of your other tables...so, with that caveat...
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim itemType as String
itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #
if itemType="Books" Then
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
End If
If itemType="Multimedia" Then
mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (#parm1,#parm2,...)
mycommand.Parameters.Clear()
mycommand.Parameters.AddWithValue("#param1",value)
' etc
mycommand.ExecuteNonQuery()
' Then repeat by changing command text for third table
' clearing/defining parameters, then executing the query
End If
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
All we're doing here is "resetting" the "mycommand" variable with a new INSERT statement, clearing the parameters, and redefining them for the second and third inserts. Note that the connection isn't closed until after all three inserts have fired. You'll obviously need to replace the "placeholders" of "field1,field2" and #param1,#param2 etc with the actual fields from your tables, but I think that should give you a push in the right direction.

Update MS Access via vb.net

the below code runs without error, but the MS Access table isn't updating. What am I missing?
Try
cnn = New OleDbConnection(ConfigurationManager.ConnectionStrings("accConnectionString").ToString())
cnn.Open()
Catch ex As Exception
Debug.Print("Oops - no connection to database")
Exit Sub
End Try
Dim sql As String
sql = "SELECT * FROM tblSend WHERE UploadedSuccessfullyOn is null ORDER BY QueuedOn;"
Dim da As New OleDbDataAdapter(sql, cnn)
Dim ds As New DataSet
da.Fill(ds, "dsQueuedToSend")
For Each dr As DataRow In ds.Tables("dsQueuedToSend").Rows
' Perform other unrelated tasks in this space, removed for brevity
' If those other tasks were successful, update Access.
If success = True Then
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #uploadedOn WHERE (([UploadID]) = #uploadId);"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.Parameters.Add("#uploadedOn", OleDbType.Date).Value = Now
cmd.Parameters.Add("#uploadedId", OleDbType.Integer).Value = dr("UploadID")
cmd.ExecuteNonQuery()
cmd.Dispose()
Console.WriteLine("Success: updated.")
Else
Console.WriteLine("Failed: Not updated.")
End If
Next
da.Dispose()
cnn.Close()
I've also tried with:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = ? WHERE (([UploadID]) = ?);"
Or simply add the values in the not-preferred/non-parameter approach:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #" & Now & "# WHERE (([UploadID]) = " & dr("UploadID") & ");"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
None of these approaches updates the MS Access table. Ideas? Thanks!
One thing I have been caught by before with Visual Studio is that when embedding an Access database in a WinForms project, when you run the project, the Access database is copied over from the original to the runtime directory, overwriting any changes you've made.
This can create the illusion that an update is not taking place, when in fact if you check at the right moment, it is.

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