Update Query Doesn't Work But No Error - sql

(I code VB.NET and use ms access 2016 as database)
I execute this query but nothing happen. I wonder whats wrong. no error when i run it. i debugged it and all the values in the variables are also correct.
no changes happened in my db too
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
End With
ButtonEdit.Text = "EDIT"
ButtonEdit.Image = My.Resources.edit
GroupBox1.Enabled = False
ButtonNew.Enabled = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MsgBox("Data cannot be empty!")
End If

The problem is that MS Access doesn't have named parameters - but rather positional parameters.
So you must specify the parameters in the correct order in which they appear in your SQL statement. And you're not doing to right now.
Change your code to this:
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
You must set the value for #nama first, before you set the value for #ide, since that's the order in which these parameters appear in your MS Access SQL statement.

Related

How to execute query and store data of a column in a variable in VB.net?

I have the following code where I am trying to execute a query and store the value from the database in two variables. Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Here is the code:
Try
Dim cn As SqlConnection
Dim strCnn As String = ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString
cn = New SqlConnection(strCnn)
cn.Open()
Dim comm As New SqlCommand("select IsCompleted, CompletionDate from managerchecklist where ID = 53 and QuestionID = 1", cn)
comm.CommandType = CommandType.Text
Dim ds As SqlDataReader
ds = comm.ExecuteReader()
If ds.HasRows Then
While ds.Read
IsComplete = ds.Item("IsCompleted").ToString()
CompleteDate = ds.Item("CompletionDate").ToString()
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End While
End If
''Close your connections and commands.
cn.Close()
Catch ex As Exception
''Handle error if any
End Try
But I seem to be going wrong somewhere. Can anyone please help me?
Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Have an If Statement to check the variables whether it is complete
If IsComplete = "complete" Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End If
Move the checking to SQL statement
Dim comm As New SqlCommand(
"select IsCompleted, CompletionDate from " +
"managerchecklist where ID = 53 and QuestionID = 1 and "
"IsCompleted = 'complete'",
cn)
Consider using parameter SQL instead to prevent SQL injection
I would recommend a Using statement for SQL queries and also parameters.
Get the values from SQL then use an IF statement to do whatever based on the values.
Assuming IsCompleted is a bit field in SQL....
Dim isCompleted As Boolean
Dim completedDate As Date
Using con As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString)
Using cmd As New SqlClient.SqlCommand("SELECT [IsCompleted], [CompletionDate] FROM managerchecklist where [ID] = #managerchecklistID and [QuestionID] = #questionID", con)
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = 53
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = 1
con.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader
While reader.Read
'Index in order of the columns in the SELECT statement
If reader.GetSqlBoolean(0).IsNull = False Then isCompleted = reader.GetSqlBoolean(0)
If reader.GetSqlDateTime(1).IsNull = False Then completedDate = reader.GetSqlDateTime(1)
End While
End Using
End Using
End Using
If isCompleted Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = completedDate
End If
You could place this in a Sub of it's own with managerchecklistID and questionID as arguments then set the parameter values with the arguments
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = managerchecklistID
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = questionID

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 update data in table datagridview in vb.net

i used this coding for my update button to update data in my table in datagridview but it is still shows error. i need some help to solve this problem
Dim MyItems As Integer
Dim MyItemNo As Integer
Dim ItemDescription As String
MyItems = GridViewItems.CurrentRow.Index
MyItemNo = GridViewItems.Item(0, MyItems).Value
ItemDescription = GridViewItems.Item(1, MyItems).Value
Dim SqlQuery As String = " UPDATE ITEMS = '" & MyItems & "'WHERE Item_No = " & MyItemNo & ""
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
Your use of the UPDATE sql statement is wrong. The correct syntax is
UPDATE <tablename> SET <field1> = <value>, <field2> = <value> WHERE <field3> = <value>
but there is also the problem of string concatenation that should be addressed.
So you could rewrite your code as
Dim SqlQuery As String = "UPDATE yourTableName SET ITEMS = ? WHERE Item_No = ?"
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#p1", MyItems)
.Parameters.AddWithValue("#p2", MyItemNo)
.ExecuteNonQuery()
End With
This is an example of a parameterized query. You should always use this approach when you need to pass values submitted by your user to your database. Without this your code is open to SQL Injection and other parsing problems

VB.Net Update doesn't update my database

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())

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