my update statement not working .. there is no effect on database when i check it
here is the code
conn.Open()
Try
Dim update As New OleDbCommand
update.Connection = conn
update.CommandText = " update O_name set fname = ' " & Name1.Text & " ' where ID = ' " & ID.Text & " ' "
update.ExecuteNonQuery()
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
conn.Close()
Using connection As New OleDbConnection(connectionString)
Using command As New OleDbCommand("update O_name set fname =? where ID =?", connection)
command.Parameters.AddWithValue("p1", Name1.Text)
command.Parameters.AddWithValue("p2", ID.Text)
command.Connection.Open()
command.ExecuteNonQuery()
MsgBox("done")
End Using
End Using
use parameters but you need to specify parameters by using ?, because :
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
UPDATE:
You have additional spaces in your parameter value assign, try below
update.CommandText = String.Format("UPDATE O_name SET fname ='{0}' WHERE ID ='{1}'",Name1.Text, ID.Text)
Related
Good morning,
I am having trouble understanding the # parameter in vb.net. if we take the example code for the msdn:
' Update the demographics for a store, which is stored
' in an xml column.
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = #demographics " _
& "WHERE CustomerID = #ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
' Use AddWithValue to assign Demographics.
' SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml)
There seem to be no problem at all, however when you try to add more parameters into the mix, it does not seems to work. What would be the correct syntax to add more than one parameter?
Here is my piece of code:
query &= "INSERT INTO "
query &= imageProcAlgo.GetSqlTable()
query &= " ( #dateTimeStampCol , #numberOfBlobsCol , #AvgLengthCol , #avgWidthCol ) "
query &= "Values (#dtsvalue, #nbOfBlobsValue, #avgLengthValue, #avgWidthValue)"
and here where I try to add values to those parameters:
Using conn As New SqlConnection(connectStr)
Using comm As New SqlCommand(query)
With comm
.Connection = conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("#dateTimeStampCol", "DateTimeStamp")
.Parameters.AddWithValue("#numberOfBlobsCol", "NumberOfBlob")
.Parameters.AddWithValue("#AvgLengthCol", "AvgWidth")
.Parameters.AddWithValue("#avgWidthCol", "AvgLength")
.Parameters.AddWithValue("#dtsvalue", "CURRENT_TIMESTAMP")
.Parameters.AddWithValue("#nbOfBlobsValue", imageProcAlgo.GetnumberOfBlobs().ToString())
.Parameters.AddWithValue("#avgLengthValue", imageProcAlgo.GetAvgWidth())
.Parameters.AddWithValue("#avgWidthValue", imageProcAlgo.GetAvgLength())
End With
Try
conn.Open()
comm.ExecuteNonQuery()
conn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
When I try to execute this piece of code, I get an error saying that #datetimestampcol and so on are not valid column names.
I don't seem to understand what is the difference between the MSDN anf my code but i feel pretty close.. Any pointers for me to understand a bit better? to figure out where I went wrong?
Thanks,
Here is the code I am using :
Try
Dim SqlQuery As String = "DELETE FROM tblEXcel WHERE ID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record deleted..")
Catch ex As Exception
MsgBox(ex.Message, vbOKOnly, "Clear Measurement Table!")
End Try
For DataBindings you can use this...
Do While ExampleBindingSource.Count > 0
ExampleBindingSource.RemoveCurrent()
Loop
Remove WHERE ID = " & id. Then ALL the rows will be deleted.
So, simply change your SQL command to:
Dim SqlQuery As String = "DELETE FROM tblEXcel"
use below statement:
delete * from tblName
Dim SqlQuery As String = "DELETE * FROM tblEXcel WHERE ID = " & id & ";"
Dim MySQLCON As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=test;User ID=root;Password=mysql;")
Dim COMMAND As MySqlCommand
MySQLCON.Open() /Open your Connection
Dim DELETERECORD As String = "DELETE * FROM tblEXcel WHERE ID= #id"
COMMAND = New MySqlCommand(DELETERECORD, MySQLCON)
COMMAND.Parameters.AddWithValue("#id", userID.Text) /userID.Text is the string of the users ID
COMMAND.ExecuteNonQuery()
MySQLCON.Close() /Always Close your Connection
MySQLCON.Dispose() /Always Dispose of your Connection
Note:
The way you where doing it was vulnerable to MySQL Injection Attacks. If you have a lot of MySQL Code in your application, i advise you to rewrite it in the way so it is not vulnerable.
I want to concat(add to what already exist) to an access cell using the text from a vb.net textbox. I tried using UPDATE but I'm getting a syntax error. This is what I tried so far
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password=matt"
Dim db As String = "Update INTO Equipment set TypeItem = ISNULL(TypeItem, '') & #EquipmentItem WHERE EquipmentCat = #category"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = New OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("#EquipmentItem", OleDbType.VarWChar).Value = Form4.TextBox1.Text & ";"
cmd.Parameters.Add("#category", OleDbType.VarWChar).Value = Me.item_text.Text
Using reader = cmd.ExecuteReader()
'some code...
End Using
End Using
End Using
The correct syntax for an Update query is
UPDATE tablename SET field=value, field1=value1,.... WHERE condition
Then you need to remove that INTO that is used in the INSERT queries
Dim db As String = "Update Equipment set TypeItem = .... " &
"WHERE EquipmentCat = #category"
After fixing this first syntax error, then you have another problem with ISNull
ISNull is a boolean expression that return true or false.
If you want to replace the null value with an empty string you need the help of the IIF function that you could use to test the return value of ISNull and prepare the base string to which you concatenate the #Equipment parameter.
Something like this
Dim db As String = "Update Equipment " & _
"set TypeItem = IIF(ISNULL(TypeItem),'', TypeItem) & #EquipmentItem " & _
"WHERE EquipmentCat = #category"
I have an update sql statement that runs perfect to update a record in msaccess via vb.net. Is there anyway to turn it into a delete statement as well? So i have a button to update the record and if i want to Delete the record.
Code for the update:
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
'sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, Description=#Description, Field1=#Field1 WHERE ID='" & TextBox5.Text & "'"
'WHERE YearofFilm='" & TextBox2.Text & "'"
'sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, Description=#Description, " & "Field1=#Field1 WHERE ID='" & TextBox5.Text & "'"
sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, " & _
"Description=#Description, Field1=#Field1 WHERE ID=#id"
Dim cmd As New OleDbCommand(sqlupdate, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.AddWithValue("#Title", TextBox1.Text)
cmd.Parameters.AddWithValue("#YearofFilm", Convert.ToInt32(TextBox2.Text))
cmd.Parameters.AddWithValue("#Description", TextBox3.Text)
cmd.Parameters.AddWithValue("#Field1", TextBox4.Text)
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(TextBox5.Text))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
Me.Close()
RefreshDGV()
should be something like this
Dim ConnString As String = "yourConnectionString"
Dim SqlString As String = "Delete From Table1 Where ID=#id"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(TextBox5.Text))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Greetings!
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())