execute multiple command for update vb.net - 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()

Related

Delete record from SQL database in VB.NET

I want to delete a record which is related to the SerialNo in the database.
This is my code:
Using con = New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database)
con.Open()
Dim sqlText = "DELETE * FROM datatable WHERE SerialNo = #ulogin"
Using cmd = New MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", frmmain.txtinput.Text)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
This code doesn't work. When I run the program, the following error appears:
Please be kind enough to suggest a suitable solution.
NOTE: 221 means the entered number.
The * does not belong. You can't delete only specific columns from a record. You either delete the whole record or do nothing, and so there is no column list portion to a DELETE statement.
While I'm here, there's no need to call con.Close() (the Using block takes care of that for you) and it's better to avoid AddWithValue() in favor of an Add() overload that lets you be explicit about your parameter type.
Const sqlText As String = "DELETE FROM datatable WHERE SerialNo = #ulogin"
Using con As New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database), _
cmd AS New MySqlCommand(sqlText, con)
cmd.Parameters.Add("#ulogin", MySqlDbType.Int32).Value = frmmain.txtinput.Text
con.Open()
cmd.ExecuteNonQuery()
End Using

Solve error in update query

I have code that throws an error - I need your help to solve it.
The error is
Syntax error in update statement
My code:
Try
Dim conn As OleDbConnection = New OleDbConnection(My.Resources.ConnectionString)
Dim cmd As OleDbCommand
conn.Open()
Dim Sql As String = "select * from Administretor"
cmd = New OleDbCommand(Sql, conn)
Dim userE, userR As String
userE = txtOldPass.Text
Dim reder As OleDbDataReader = cmd.ExecuteReader()
While reder.Read()
userR = reder.Item(0)
End While
If userE = userR Then
If txtNewPass.Text = txtNewConfromPass.Text And txtNewConfromPass.Text <> "" And txtNewPass.Text <> "" Then
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Dim cmd0 As OleDbCommand = New OleDbCommand(Sql, conn)
cmd0.ExecuteNonQuery()
Else
MsgBox("Make sure that you have entered new password in both text Box and they both are same...!")
End If
Else
MsgBox("Enter the correct Username")
End If
MsgBox("Done 2")
Catch ex As OleDbException
MsgBox(ex.Message)
End Try
Two errors
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
Missing single quote here---+ |
|
LogIn_Id will never equal the old password--------------------------------+
But apart from the simple syntax errors you have a huge SQL injection vulnerability from building the SQL out of pieces including user input.
In this part,
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where ...
The PASSWORD will have a single quote before it, and no single quote after it.
Change it to:
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & "' where ...
Notice the extra single quote here ----------------------------------------^
Add this syntax :
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Clipboard.SetText(Sql)
The query will be in your clipboard. Run it on SQL(whichever you are using), and see if the query runs smoothly?
Please show us what the query generation holds and what the error it produce when running directly from the SQL.

"variable" is not declared error

Image of the error
I am new to Vb.net programing and I need a little help here, I pretend to send info to my database, the first query gives me the id I need and I declare it as "postoid", when I later try to call it (in the insert into part) it says it is not declared, I have googled the problem a hundred times but I couldn't find the answer.
Ps: this code is all in the same private sub
Try
mysqlconn.Open()
queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
READERuser = COMMANDuser1.ExecuteReader
While READERuser.Read
Dim postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
Catch ex As Exception
End Try
Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand
With sqlcommand
.CommandText = sqlquery
.Connection = mysqlconn
.ExecuteNonQuery()
End With
MsgBox("Computador Adicionado")
Dispose()
Close()
Your variable postoid is out-of-scope outside the block it is declared in.
All you need to do is declare it outside the Try structure:
Dim postoid As String = ""
queryrow = "Select postos_id from postos where postos_nome = #PostosNome"
Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
COMMANDuser1.Parameters.Add("#PostosNome", TextBox1.Text)
mysqlconn.Open()
READERuser = COMMANDuser1.ExecuteReader()
While READERuser.Read
postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
End Using
If postoid <> "" Then
' perform the insert...
I did not actually use Try in that, as you have no code in your Catch block - having no code in the Catch block has the effect of hiding errors. You want to see the errors.
For using SQL parameters, see, e.g., Inserting data into a MySQL table using VB.NET but please use .Add instead of .AddWithValue - the latter will not always work as intended.

Getting error while running the query [duplicate]

This question already has an answer here:
Why error ???? Syntax error in INSERT INTO statement
(1 answer)
Closed 7 years ago.
Here is my code.
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\speednet\speed_net.accdb")
Dim com As New OleDbCommand
con.Open()
com.Connection = con
com.CommandText = "insert into users (name,username,password,user_type) values ('" & name1.Text & "' ,'" & username.Text & "' ,'" & password.Text & "','" & account_type.Text & "')"
com.ExecuteNonQuery()
The error:
Syntax error in insert into statement ...
Cant find out the problem.
Password is a reserved keyword in access. You need square brackets around that word.
But your query should also be modified to use a parameter approach instead of string concatenation, otherwise more dangerous situation will be possible. Read about Sql Injection and what happen if one of your concatenated string contains a single quote.
So
Using con = New OleDbConnection("....")
Using com = New OleDbCommand("insert into users " & _
"(name,username,[password],user_type) " & _
"values (#name, #uname,#pass,#acctype)", con)
con.Open()
com.Parameters.AddWithValue("#name", name1.Text)
com.Parameters.AddWithValue("#uname", username.Text)
com.Parameters.AddWithValue("#pass", password.Text)
com.Parameters.AddWithValue("#acctype", account_type.Text)
com.ExecuteNonQuery()
End Using
End Using

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.