Update query not working in Vb.NET - vb.net

i am trying to update the database using update but for some reason database is not getting updated
i used following query:
Dim dc As OleDbCommand
dc = New OleDbCommand("UPDATE tempM1 SET [input] = '" & ans_selected & "' WHERE question = '" & question & "'", cn)
dc.ExecuteNonQuery()
i am using 1 more update query and its working fine:
dc = New OleDbCommand("UPDATE tempTof SET [input] = '" & optionSelected & "' WHERE question = '" & question & "'", cn)
dc.ExecuteNonQuery()
please help... i wasted almost 2 hours figuring out whats wrong but couldnt debug it.

You should always use parametrized query, also I don't see in your code where you open the connection
Dim cn As OleDbConnection
Using(cn = GetConnection())
cn.Open();
Dim dc As OleDbCommand
dc = New OleDbCommand("UPDATE tempM1 SET [input] = ? WHERE question = ?", cn)
dc.Parameters.AddWithValue("#ans", ans_selected)
dc.Parameters.AddWithValue("#question", question)
dc.ExecuteNonQuery()
End Using

Dim dc As OleDbCommand
dc = New OleDbCommand("UPDATE tempM1 SET [input] = '" & ans_selected & "' WHERE question = '" & question & "'", cn)
put something in here to examine dc.CommandText such as:
Console.WriteLine dc.CommandText
dc.ExecuteNonQuery()
Does dc.CommandText really contain what you expect it to contain?
If it does, and it says something like
UPDATE tempM1 SET [input]='foo' WHERE question='bar'
Then double check by going direct to the database and checking that substituting the UPDATE for a SELECT returns at least one row:
SELECT * FROM tempM1 WHERE question='bar'
If all those steps are satisfactory and you're still stuck:
Double check the connectionstring is truly pointing to the same database you think it is.
Bypass your code and execute the UPDATE command yourself directly in the underlying database and check that's being allowed.

Related

No value given for one or more required parameters error vb.net

no_hp = TextBox1.Text
alamat = TextBox2.Text
password = TextBox3.Text
cmd = New OleDbCommand("UPDATE [user] SET no_hp = '" & CInt(TextBox1.Text) & "',alamat = " & TextBox2.Text & ", pin ='" & CInt(TextBox3.Text) & "' WHERE id = " & id & "", conn)
cmd.Connection = conn
cmd.ExecuteReader()
i was trying to update my access database with the following error
i cant seem to see where i did wrong
i already changed the data type from the textbox to match with the data types used in the database
the no_hp and pin is integer so i converted it to Cint but it doesnt seem to work
i already tried to substitute it to a variable but still it didnt work
please tell me where i did wrong
Use Parameters to avoid SQL injection, a malious attack that can mean data loss. The parameter names in Access do not matter. It is the order that they are added which must match the order in the SQL statement that matters.
The Using...End Using statements ensure that you objects are closed and disposed even it there is an error. This is most important for connections.
You con't need to set the connection property of the command because you passed the connection in the constructor of the command.
ExcuteReader is for retrieving data. Use ExecuteNonQuery to update, insert of delete.
Private Sub UpdateUsers()
Using conn As New OleDbConnection("Your connection string")
Using cmd = New OleDbCommand("UPDATE [user] SET no_hp = ?,alamat = ?, pin =? WHERE id = ?", conn)
cmd.Parameters.Add("nohp", OleDbType.Integer).Value = CInt(TextBox1.Text)
cmd.Parameters.Add("alamat", OleDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("pword", OleDbType.Integer).Value = CInt(TextBox3.Text)
cmd.Parameters.Add("id", OleDbType.Integer).Value = id
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

Populating DataGriView/ComboBox Parameterized MySQL AES_ENCRYPT / AES_DECRYPT

Still moving to MySQL AES_ENCRYPT/AES_DECRYPT with Parameterized Queries, I finished translating many parts of the code like: INSERT, SELECT, UPDATES, etc. for textboxes and labels. By now I need some orientation to Populating DataGridViews and ComboBoxes with MySQL Parameterized Query.
e.g.
Dim SQL As String = "SELECT AES_DECRYPT(`AG_Nom`, '" & MyPass & "') AS #UserName, AES_DECRYPT(`AG_Pic`, '" & MyPass & "') AS #UserPic FROM `Agents`"
Or if possible use something:
Dim SQL As String = "SELECT * FROM `Agents`"
With AES_DECRYPT and Parameterized values to fill the controls
I tried many unsuccessfully options; my biggest question is how to pass the content of #Varibles to populate the controls.
The follow code not works:
Dim SQL As String = "SELECT AES_DECRYPT(`AG_Nom`, '" & MyPass & "') AS #UserName, AES_DECRYPT(`AG_Pic`, '" & MyPass & "') AS #UserPic FROM `Agents`"
MySQLConn.Open()
command.Parameters.AddWithValue("#MyPass", AESPass)
Dim dt As New DataTable()
dt.Load(command.ExecuteReader())
DataGridView3.DataSource = dt
MySQLConn.Close()
MySQLConn.Dispose()
The old way works, of course, show undecrypted string:
MySQLConn.Open()
Dim dt As New DataTable()
dt.Load(cmd.ExecuteReader())
DataGridView3.DataSource = dt
MySQLConn.Close()
I would appreciate your feedback to keep improving my code.
TIA
I solved my own question!
Dim SQL As String = "SELECT AES_DECRYPT(`AG_Nom`, '" & MyPass & "') AS #UserName, AES_DECRYPT(`AG_Pic`, '" & MyPass & "') AS #UserPic FROM `Agents`"
Dim command = New MySqlCommand(SQL, MySQLConn)
MySQLConn.Open()
command.Parameters.AddWithValue("#MyPass", MyPass)
Dim Reader As MySqlDataReader = command.ExecuteReader()
While Reader.Read
DataGridView1.Rows.Add(Reader.GetString("UserName"), Reader.GetString("UserPic"))
End While
MySQLConn.Close()
MySQLConn.Dispose()
I hope this help to many other developers
:)

How to update multiple data to Database?

Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc

execute multiple command for update vb.net

i am working on a vb project . in this i need to save some record to one table and update some records in another table in one event or click .. i am doing like this .
dim simpan as new sqlcommand
conn = New SqlConnection(connectionstring)
conn.Open()
simpan = New SqlCommand()
simpan.Connection = conn
simpan.CommandType = CommandType.Text
simpan.CommandText = "update barang set (nama_barang,harga)values(" & TextBox3.Text & ",'" & TextBox4.Text & "') where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()
tampil()
MsgBox("Data Berhasil Diubah", MsgBoxStyle.Information, "Informasi")
conn.Close()
but it giving error as "incorrect syntax near '('" .. i am not getting where i go wrong .. please help me
I see a couple issues with this...
Your Syntax is wrong on your update statement (Al-3sli beat me to that one).
Your textbox values will cause issues if a user types a single quote in the text box (For Example: The word "Wasn't".
Add the replace function to each textbox TextBox3.text.Replace("'","''") That will replace single ticks with two single ticks.
You might also consider using parameterized queries
You can't use update like this, change your code like so:
simpan.CommandText = "update barang set nama_barang = '" & TextBox3.Text & "',harga ='" & TextBox4.Text & "' where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()

Sql query to update new values to column Visual Basic

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.
Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.