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

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

Related

How solve this problem syntax error in UPDATE statement

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

How to fix "Invalid attempt to read when reader is closed vb.net"

invalid attempt to read when reader is closed error. vb.net
I have the code below that I use to login into MySQL but it keeps displaying the error 'invalid attempt to read when reader is closed' and then it logs in. I don't understand what could still be wrong with the code. Kindly assist, it's so frustrating. Thanks.
Try
ConnDB()
command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
Reader = command.ExecuteReader()
If Reader.Read = True Then
ComboBox1.Text = Reader.GetValue(2)
lblUser.Text = Reader.GetValue(3)
End If
If (Reader IsNot Nothing) Then
Reader.Close()
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
If ComboBox1.Text.Length > 0 Then
MainMenu.lblUserName.Text = Me.txtUsername.Text
MainMenu.lblType.Text = Me.ComboBox1.Text
MainMenu.lblOccupation.Text = Me.ComboBox1.Text
MainMenu.lblUser.Text = Me.lblUser.Text
Dim st As String = "Successfully logged in"
LogFunc(txtUsername.Text, st)
Me.Hide()
MainMenu.Show()
Else
MsgBox("Incorrect username or password..Login is Failed...Try again !", MsgBoxStyle.Critical, "Login")
txtUsername.SelectAll()
txtPassword.SelectAll()
txtUsername.Focus()
txtPassword.Text = ""
End If
command.Dispose()
' Reader.Close()
'command.Dispose()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
DisconnMy()
End Try
I expect it to log in successfully without displaying the error.
Sorry, I forgot to add this for my connection string.
Public Sub ConnDB()
con.Close()
Try
con.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "user id = '" & UserNameMySQL & "'; " _
& "password = '" & PwdMySQL & "'"
con.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
In general it's not a good idea to use a "global", single connection for everything. Note that connection-pooling is enabled by default which means that .NET will take care of the physical connections. So you should create,open,use and close/dispose the connection where you use it.
I'm pretty sure that this will fix the issue:
Try
Using con As New MySql.Data.MySqlClient.MySqlConnection(MySettings.Default.SqlConnection)
Using command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
con.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
ComboBox1.Text = reader.GetValue(2)
lblUser.Text = reader.GetValue(3)
End If
' NOTE: you dont need to close the reader/command/connection
' if you use the Using-statement, it will use Dispose even in case of an error
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

How to execute rd.HasRow properly without affecting uploading photo to database?

I'm trying to use rd.HasRow method to validate whether the data typed in is duplicated or not before saving it to the database.
If it is duplicated, it is suppose to pop-up the error message box instead of saving the data.
How am I suppose to execute this along with the code I'm using to upload a photo to the database? If I comment this part of code, the typed in data (not duplicated) can be saved to database but the photo will not uploaded along with it.
'i = cmd.ExecuteNonQuery()
'If i >= 1 Then
'MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
'Else
'MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
'End If
But if I don't, the data typed in by the user will not be saved and this error message will pop-up against i=cmd.ExecuteNonQuery():
System.InvalidOperationException: 'There is already an open DataReader associated with this Command which must be closed first.'
This is the overall code.
Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rollno As String
Dim name As String
Dim gender As String
Dim address As String
Dim phoneno As Integer
Dim datereg As String
Dim faculty As String
Dim course As String
Dim semester As String
Dim i As Integer
Dim j As Integer
rollno = TextBox1.Text
name = TextBox2.Text
gender = ComboBox4.Text
address = TextBox3.Text
phoneno = TextBox4.Text
datereg = dateTimePicker1.Value
faculty = comboBox1.Text
course = comboBox2.Text
semester = comboBox3.Text
con.ConnectionString = "Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True"
cmd.Connection = con
con.Open()
'To validate whether duplication of typed in data by user occurs or not, if yes, error msg pop-up. If no, proceed and save the data into database
Dim rd As SqlDataReader
cmd.CommandText = "SELECT * FROM Profile WHERE RollNo= '" & TextBox1.Text & "' and Name='" & TextBox2.Text & "'"
rd = cmd.ExecuteReader()
If rd.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
End If
'i = cmd.ExecuteNonQuery()
'If i >= 1 Then
'MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
'Else
'MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
'End If
con.Close()
con.Open()
'To save the uploaded photo to table Photo
Dim command As New SqlCommand("Insert into Photo (Img, Pid) Values (#Img, #Pid)", con)
command.Connection = con
Dim ms As New MemoryStream
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
command.Parameters.Add("#Img", SqlDbType.Image).Value = ms.ToArray()
command.Parameters.Add("#Pid", SqlDbType.VarChar).Value = TextBox1.Text
j = cmd.ExecuteNonQuery()
If j >= 1 Then
MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
The code looks a little messy and, in my experience at least, it can be difficult to debug messy code. There are a few things we can do to rectify that and I'll attempt to do that now with you.
First, give meaningful names to your controls. You can do this through the design on your form by selecting the control and changing the Name property. This will massively help you when referring to them through code. In this instance it will also help you eliminate the need for variables.
Consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
This will help you manage your declarations and resources whilst also creating a clearer picture of your code.
I would also consider breaking each command into it's own Using block in an attempt to make your code clearer.
When inserting data into a database consider using SQL parameters to avoid SQL injection.
Finally onto the code, let's look at each Using block in turn.
First, I would start by initiating the SqlConnection within a Using block and then we can use that connection for each command:
Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
con.Open()
'Add the rest of the code here
End Using
Checking the record exists:
Here, considering declaring a Boolean variable which we use to determine if the record exist.
Dim recordExists As Boolean = False
Using cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo = #RollNo AND Name = #Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
cmd.Parameters.Add("#Name", SqlDbType.[Type]).Value = txtName.Text
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
Show prompt if the record exists or insert into the database if it doesn't:
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using cmd As New SqlCommand("INSERT INTO Profile VALUES (#RollNo, #Name, #Gender, #Address, #PhoneNo, #DateReg, #Faculty, #Course, #Semester)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
cmd.Parameters.Add("#Name", SqlDbType.[Type]).Value = txtName.Text
cmd.Parameters.Add("#Gender", SqlDbType.[Type]).Value = cboGender.Text
cmd.Parameters.Add("#Address", SqlDbType.[Type]).Value = txtAddress.Text
cmd.Parameters.Add("#PhoneNo", SqlDbType.[Type]).Value = txtPhoneNo.Text
cmd.Parameters.Add("#DateReg", SqlDbType.[Type]).Value = dtpDateReg.Value
cmd.Parameters.Add("#Faculty", SqlDbType.[Type]).Value = cboFaculty.Text
cmd.Parameters.Add("#Course", SqlDbType.[Type]).Value = cboCourse.Text
cmd.Parameters.Add("#Semester", SqlDbType.[Type]).Value = cboSemster.Text
If cmd.ExecuteNonQuery() > 0 Then
MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
End If
Inserting the image:
Using cmd As New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (#Img, #Pid)", con)
Using ms As New MemoryStream()
pbxImage.Image.Save(ms, pbxImage.Image.RawFormat)
cmd.Parameters.Add("#Img", SqlDbType.Image).Value = ms.ToArray()
cmd.Parameters.Add("#Pid", SqlDbType.VarChar).Value = txtName.Text
End Using
cmd.ExecuteNonQuery()
End Using
Note that I have used SqlDbType.[Type] where I am unsure of your data type within the database. You will want to replace this with the data type you have specified for each column.
All together your code would look something like this:
Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
con.Open()
Dim recordExists As Boolean = False
Using cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo = #RollNo AND Name = #Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = txtRollNo.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using cmd As New SqlCommand("INSERT INTO Profile VALUES (#RollNo, #Name, #Gender, #Address, #PhoneNo, #DateReg, #Faculty, #Course, #Semester)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text
cmd.Parameters.Add("#Gender", SqlDbType.VarChar).Value = cboGender.Text
cmd.Parameters.Add("#Address", SqlDbType.VarChar).Value = txtAddress.Text
cmd.Parameters.Add("#PhoneNo", SqlDbType.VarChar).Value = txtPhoneNo.Text
cmd.Parameters.Add("#DateReg", SqlDbType.VarChar).Value = dtpDateReg.Value
cmd.Parameters.Add("#Faculty", SqlDbType.VarChar).Value = cboFaculty.Text
cmd.Parameters.Add("#Course", SqlDbType.VarChar).Value = cboCourse.Text
cmd.Parameters.Add("#Semester", SqlDbType.VarChar).Value = cboSemster.Text
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
End If
Using cmd As New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (#Img, #Pid)", con)
Using ms As New MemoryStream()
pbxImage.Image.Save(ms, pbxImage.Image.RawFormat)
cmd.Parameters.Add("#Img", SqlDbType.Image).Value = ms.ToArray()
cmd.Parameters.Add("#Pid", SqlDbType.VarChar).Value = txtName.Text
End Using
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
This code is untested, I haven't the environment but it should give you something to work with.
Comments and explanations in line.
Private Sub OPCode()
Dim i As Integer
Dim j As Integer
Dim rollno = TextBox1.Text
Dim name = TextBox2.Text
Dim gender = ComboBox4.Text
Dim address = TextBox3.Text
Dim phoneno = CInt(TextBox4.Text) 'Unless your phone numbers are very different
'than the phone numbers here, the likelyhood of a user entering just numbers is
'nil. Change this to a string and a VarChar in the database
Dim datereg = dateTimePicker1.Value
Dim faculty = comboBox1.Text
Dim course = ComboBox2.Text
Dim semester = ComboBox3.Text
'The Using block ensures that your connection is closed and disposed
'Pass your connection string to the constructor of the connection
Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
'Pass the Sql command text and connection to the Constructor of the command.
'NEVER, NEVER, NEVER allow user input to be passed directly to a database. Always use parameters.
Dim cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo= #RollNo and [Name]= #Name;", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = rollno
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = name
con.Open()
Using rd As SqlDataReader = cmd.ExecuteReader()
'To validate whether duplication of typed in data by user occurs or not, if yes, error msg pop-up. If no, proceed and save the data into database
If rd.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
'You don't want to go any further if the user is registered.
Exit Sub
End If
End Using
'Just use another new command variable to avoid confusion
'I think it is much better practice to list the fields.
Dim cmd2 As New SqlCommand("INSERT INTO Profile VALUES (#RollNo ,#Name,#Gender, #Address, #PhoneNo , #DateReg , #Faculty , #Course , #Semester);", con)
cmd2.Parameters.Add() 'etc.
i = cmd2.ExecuteNonQuery()
If i >= 1 Then
MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
'To save the uploaded photo to table Photo
Dim command3 As New SqlCommand("Insert into Photo (Img, Pid) Values (#Img, #Pid)", con)
command3.Connection = con
Dim ms As New MemoryStream
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
command3.Parameters.Add("#Img", SqlDbType.Image).Value = ms.ToArray()
command3.Parameters.Add("#Pid", SqlDbType.VarChar).Value = TextBox1.Text
j = command3.ExecuteNonQuery()
End Using
If j >= 1 Then
MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.
As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

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.