How solve this problem syntax error in UPDATE statement - vb.net

This problem at syntax error for update statement then I don't know how to solve this problem
Private Sub editStaff()
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
If IDTextBox.Text <> "" And FirstTextBox.Text <> "" And SecondTextBox.Text <> "" And UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
strSQL = "update Staff set First_Name = '" & FirstTextBox.Text & "', " &
"Second_Name = '" & SecondTextBox.Text & "', " & "Username = '" & UsernameTextBox.Text & "', " &
"Password = '" & PasswordTextBox.Text & "'" & " where ID = " & CInt(IDTextBox.Text) & ""
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

For some reason your validation If did not include the ID text box. I added validation for this text box. The OrElse is a short circuit. As soon as it finds a True it stops checking the conditions and proceeds to the next line.
This code
If con.State = ConnectionState.Closed Then
con.Open()
End If
is completely unnecessary if you keep your database objects local. Keeping them local allows you to ensure they are closed and disposed with Using...End Using blocks.
Don't open the connection until you need it which is directly before the .Execute... line. Use parameters to avoid Sql Injection. Also your Update statement is much easier to write without all the single quotes and double quotes and ampersands.
Caution In Access the order that the parameters appear in the Sql statement must match the order that they are added to the .Parameters collection.
Finally, you should NEVER store passwords as plain text. I will leave it to you to research salting and hashing and correct the code.
Private Sub editStaff()
Dim i As Integer
If Integer.TryParse(IDTextBox.Text, i) Then
MessageBox.Show("ID text box must be a number")
Return
End If
If IDTextBox.Text = "" OrElse FirstTextBox.Text = "" OrElse SecondTextBox.Text = "" OrElse UsernameTextBox.Text = "" OrElse PasswordTextBox.Text = "" Then
MessageBox.Show("Please fill in all text boxes")
Return
End If
Try
Using con As New OleDbConnection("Your connection string")
Dim strSQL = "Update Staff set First_Name = #FirstName, Second_Name = #SecondName, [Username] = #UserName, [Password] = #Password Where [ID] = #ID"
Using cmd As New OleDbCommand(strSQL, con)
With cmd.Parameters
.Add("#FirstName", OleDbType.VarChar).Value = FirstTextBox.Text
.Add("#SecondName", OleDbType.VarChar).Value = SecondTextBox.Text
.Add("#UserName", OleDbType.VarChar).Value = UsernameBox.Text
.Add("#Password", OleDbType.VarChar).Value = PasswordTextBox.Text
.Add("#ID", OleDbType.Integer).Value = CInt(IDTextBox.Text)
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Related

Message box won't display [duplicate]

This question already has an answer here:
Not able to show error message if the email/password wrongly entered
(1 answer)
Closed 5 years ago.
I want a message box to appear if the email/ password is incorrect when logging in. However nothing happens with this else statement. Does it need to be placed somewhere else for it to work?
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
str1 = ("SELECT * FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "' AND [Password] = '" & TxtPassword.Text & "'")
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
dr = cmd1.ExecuteReader
While dr.Read()
userFound = True
TxtPassword.Text = dr("Username").ToString
TxtUserName.Text = dr("Password").ToString
FirstNameToPass = dr("First Name").ToString
LastNameToPass = dr("Last Name").ToString
AddressToPass = dr("Address").ToString
EmailToPass = dr("Email").ToString
If userFound = True Then
UserAccountView.Show()
Me.Hide()
TxtPassword.Clear()
TxtUserName.Clear()
Else
MsgBox("Login is incorrect")
End If
End While
MyConn.Close()
End If
I would simply use a Count() to check if user exists and correct.
Note:
In NoAlias's answer it doesn't solve the problem that userFound will always be true.
So I implemented this solution there might be few errors since i'm not familiar with OleDb but nothing to big hopefully
I also implemented the Using as it is good practice to implement it when working with: IDisposable()
Using MyConn As New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
Dim check As String = "SELECT COUNT(*) FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "' AND [Password] = '" & TxtPassword.Text & "'"
Dim UserExist As Boolean = False
Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
If reader(0) = 0 Then
UserExist = False
Else
UserExist = True
End If
End While
End Using
If UserExist = True Then
Dim getData As String = "SELECT * FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "'"
Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
Using reader As OleDbDataReader = command2.ExecuteReader()
While reader.Read()
userFound = True
TxtPassword.Text = dr("Username").ToString
TxtUserName.Text = dr("Password").ToString
FirstNameToPass = dr("First Name").ToString
LastNameToPass = dr("Last Name").ToString
AddressToPass = dr("Address").ToString
EmailToPass = dr("Email").ToString
End While
End Using
Else
MsgBox("Login is incorrect")
End If
MyConn.Close()
End Using
If your SQL returns no results, which will be the case when the credentials are wrong, the MessageBox code will never be called. Put this code block after your While statement.
If userFound = True Then
UserAccountView.Show()
Me.Hide()
TxtPassword.Clear()
TxtUserName.Clear()
Else
MsgBox("Login is incorrect")
End If

Insert into database in vb not working

I have the below snippet of code whenever I try registering the username exist part seems to be executed even for a username that doesn't exist in the database. Don't know where am wrong here any help will be appreciated.
'Connecting to SQL Database and executing Query------------------------------------------
Dim Strconn As String = "Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true"
Dim Strcmd As String = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES ('" & user_name.Text & "','" & con_pass.Text & "', '" & first_name.Text & "', '" & last_name.Text & "', '" & dob.Text & "', '" & course.Text & "', '" & college.Text & "');"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Strcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
'Exception Handling-----------------------
Dim exc As Exception = Nothing
Try
da.Fill(ds)
Catch ex As Exception
exc = ex
Finally
If Not (exc) Is Nothing Then
MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist")
user_name.Focus()
Else
MsgBox("Registration Successful.", vbInformation, "Successful")
Me.Close()
Login.Show()
End If
End Try
Here is a refactor of your code with some helpful guidance. I think this will compile, but if it does not, then you can do a little homework to figure out what is missing.
Try
' the USING block guarantees that the object's Close() and Dispose() methods are fired automatically when you exit the block
Using sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true")
Using sqlcmd As SqlCommand = sqlconn.CreateCommand
With sqlcmd
.CommandType = CommandType.Text
' parameterized query to protect against SQL injection
.CommandText = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES (#username, #password, #firstname, #lastname, #dob, #course, #college)"
With .Parameters
.Clear()
.AddWithValue("#username", user_name.Text)
.AddWithValue("#password", con_pass.Text)
.AddWithValue("#firstname", first_name.Text)
.AddWithValue("#lastname", last_name.Text)
.AddWithValue("#dob", dob.Text)
.AddWithValue("#course", course.Text)
.AddWithValue("#college", college.Text)
End With
.ExecuteScalar() ' Actually executes the SQL command
End With
End Using
End Using
MsgBox("Registration successful")
Catch ex As Exception
' Any error in the TRY block will automatically jump to herem and the "ex" object will be an Exception object with populated properties
MsgBox("User name already exists. Error from database is " & ex.Message)
End Try

VB.Net ignores isDBNull condition

I'm programming a dog adoption form. It retrieves data from a Access DB then the user can adopt up to three dogs, each one of them specified in 3 different fields. I'm doing it this way because I previously tried to do it with arrays, with no luck.
The issue comes here (highlighted in bold):
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
cmd.CommandText = "select adopcion1, adopcion2, adopcion3 from usuarios where codigo_usuario = " & FormPrincipal.codigo_usuario & ""
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read()
**If dr.IsDBNull(1) Then
posicionAdopcion = 1
ElseIf dr.IsDBNull(2) Then
posicionAdopcion = 2
ElseIf dr.IsDBNull(3) Then
posicionAdopcion = 3
Else
MsgBox("Lo sentimos, solo puedes hacer un máximo de 3 adopciones")
Exit Sub**
End If
End While
dr.Close()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación.")
Me.Close()
End Try
and
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
**If (posicionAdopcion = 1) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION1 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 2) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION2 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 3) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION3 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
End If**
cmd.ExecuteNonQuery()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación...")
Me.Close()
End Try
What I'm trying to do is to check if the adoption fields (adopcion1, adopcion2, adopcion3) are empty, if they are, place the name of the dog there. If they are not, check for the next free slot. If none available, print the corresponding error message. But what the program does is to overwrite the adopcion1 (first field) no matter what.
I have checked this thread, I may be having a similar issue misunderstanding isDBNull usage, but so far I'm trying to do what it's stated there with no result.
What I'm doing wrong?
I got it, as I expected it was a silly mistake: I was retrieving the first data field from 1, and not from 0. Thus skipping it entirely:
If dr.isDBNull(0) Then
posicionAdopcion = 1
But yes, the code seems clunky, didn't know about SQL parameters, going to check them ASAP.
Thanks for the help!

Insert multiple data into a single cell SQLyog vb.net

I am trying to develop a management system for dentists, this the system i am developing
THIS MY PROGRAM'S SCREENSHOT
when the dentist inputted a data on a textbox, it will be saved on the database and whenever the dentist insert a data again on that textbox, instead of replacing the older data with a newer data, it will store the data, making the cell store multiple data
and this is my code for adding data into the table
table name: teethhistory
database name: PatientManagementSystem
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
If e.KeyCode = Keys.Enter Then
MySqlConn.Open()
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar ='" & txtURThirdMolar.Text & "' WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.close()
End If
End Sub
if you want to Append the Existing text In field with new data from textbox,use Update command as
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
for inserting values seperated by commas, just insert a comma before the string ion concat function.
hope i undestood your problem well and this solves it.

How to prevent certain data from being inserted into the database with If Else statements?

I have two comboboxes, a messagebox and a Send button. When the app startups and I click on the Send button with the comboboxes and messagebox empty, a pop-up box comes up and says "Select a client" After doing this, I go back to the database and see that it has added a new record to that table, even though I didn't put in any data after clicking on the "Send" button. Same applies for when one of the three controls I have has data in it, but the other two don't, and the program asks me to enter that data before it succeeds. But it still adds the record despite having those If Statements. What am I doing wrong?
My code:
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
MsgBox("Message Sent")
End If
con.Close()
End Using
I think you want something like this (note this does not address parameterization concerns):
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
End If
con.Close()
End Using
Similar solution to #OldProgrammer, with an attempt at parameterized insert.
Private Sub SendButton_Click(sender As System.Object, e As System.EventArgs) Handles SendButton.Click
Try
If writeMessage() Then
MessageBox.Show("Message sent.", "Success")
End If
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred sending this message:", ex.Message))
End Try
End Sub
Private Function writeMessage() As Boolean
If isValidMessage() Then
writeMessageInfo()
Return True
End If
Return False
End Function
Private Sub writeMessageInfo()
Using con As New SqlConnection(yourConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.Parameters.Add(New SqlParameter("clientValue", cboClient.Text))
cmd.Parameters.Add(New SqlParameter("userValue", cboUser.Text))
cmd.Parameters.Add(New SqlParameter("messageText", rtfMessage.Text))
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values(#clientValuem, #userValue, #messageText)"
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Function isValidMessage() As Boolean
If cboClient.SelectedIndex = -1 Then
MessageBox.Show("Please select a client.", "Missing info")
cboClient.Focus()
Return False
End If
If cboUser.SelectedIndex = -1 Then
MessageBox.Show("Please select a user.", "Missing info")
cboUser.Focus()
Return False
End If
If rtfMessage.Text = String.Empty Then
MessageBox.Show("Please enter a message.", "Missing info")
rtfMessage.Focus()
Return False
End If
Return True
End Function