how to detect wrong input from user vb - mysql

I want my system to detect wrong input from the user . for example I use " matric_no " as the primary key in my database and data for the primary key is a " D1233455 " . when the user wants to delete a record in the database , they must type the primary key and then pressing the delete button . but if the primary key is entered incorrectly , the system will continue to detect errors when the delete button is pressed , and I do not have to restart my program to correct the input.I used the coding to link the database.
but the problem is everything that i explained above not happened..i have to restart my system to enter new correct input. i hope someone can help me..The most important is i want to know how to detect wrong input from user. i already found how to enter new input without restarting my system...help me please..
Dim query As String = "delete from Student_Database where Matric_No = '" & TextBox1.Text & "'"
Dim query1 As String = "delete from Fee_Database where Matric_No = '" & TextBox1.Text & "'"
If Me.TextBox1.Text = String.Empty Then
Notify the user of the invalid value.
MessageBox.Show("Please enter a value.", _
"Required Field", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
ElseIf ("I need the solution for this part") Then
MessageBox.Show("Record cannot be trace. Please enter the correct ID", "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
objResult.queryCommand(query)
objResult.queryCommand(query1)
MessageBox.Show("Record has been deleted.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

Is there a specific syntax of how you want your value to be. You have mentioned it as "D1233455" and if it is always in that format, then you can just compare the first character of the input and count the the length of the input which should be 8. If these conditions are false then it should show a message box stating the value is invalid.

You need a select query that select all the matric_no rows, then compare it with value on your textbox.
And in case that I'm using the MS-Access database, so I use OleDb connection, if you're using another database, just change the connection to what you use.
Here the connection what I use
Imports System.Data.OleDb
Module Connection
Public Conn As New OleDbConnection
Public CMD As OleDbCommand
Public DA As OleDbDataAdapter
Public DR As OleDbDataReader
Public DS As DataSet
Public DT As DataTable
Public STR As String
Public Sub Connect()
Try
STR = "provider=microsoft.ACE.OLEDB.12.0;data source=" & Application.StartupPath & "\your_database_name_here.mdb"
Conn = New OleDb.OleDbConnection(STR)
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Catch ex As Exception
MsgBox("Failed to connect database")
End Try
End Sub
End Module
Then here the code for your problem
'Add this to the top of the code
'Actually before the `Public Class <your_form_name>`
'So it's like
Imports System.Data.OleDb
Public Class blablabla
.....
Private Sub DeleteData()
Dim query As String = "delete from Student_Database where Matric_No = '" & TextBox1.Text & "'"
Dim query1 As String = "delete from Fee_Database where Matric_No = '" & TextBox1.Text & "'"
'Changes
Dim query2 As String = "SELECT * FROM Student_Database where Matric_No = '" & TextBox1.Text & "'" 'This query to detect that user input is same to any Matric_No rows.
Connect()
CMD = New OleDbCommand(query2, Conn)
DR = CMD.ExecuteReader
DR.Read
If DR.HasRows Then
If Me.TextBox1.Text = String.Empty Then
Notify the user of the invalid value.
MessageBox.Show("Please enter a value.", _
"Required Field", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Else
objResult.queryCommand(query)
objResult.queryCommand(query1)
MessageBox.Show("Record has been deleted.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else 'Here you detect the wrong input
MessageBox.Show("Record cannot be trace. Please enter the correct ID", "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
Conn.Close()
End Sub
Hope those help you.

Related

VB.NET Refresh DataGridView function works with insert and delete commands but not with update

I have a form on VB.NET with which I manage data for a mysql database.
The form, in addition to the various fields for entering data (textboxes + 1 datepicker), includes a "Save" button (which turns into "Update" when I press the "Edit" button), an "Edit" button, a "Delete" button and a DataGridView.
I have created a ShowData () to display the data in the DataGridView.
This function works on the form load, it works also when I use the "Save" command (with the mysql Insert command) and the "Delete" command (with the mysql Delete command) but it seems to create problems when I use the "Update" command.
When I use the "Update" command the data is updated in the database but the "ShowData ()" function gives me the error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 and, consequently, the data inside the DataGridView is not updated.
The "ShowData ()" function is also present on the "CellMouseDown" event of the DataGridView. The same error only shows up when I use the "Update" command first and then I move through the rows.
Public Class
Dim Connection As New MySqlConnection("server=localhost; user=root; password=; database=dbname")
Dim MySQLCMD As New MySqlCommand
Dim MySQLDA As New MySqlDataAdapter
Dim DT As New DataTable
Dim Table_Name As String = "tablename"
Dim Dati As Integer
Dim LoadImagesStr As Boolean = False
Dim data1Ram, data2Ram As String
Dim StatusInput As String = "Save"
Dim SqlCmdSearchstr As String
ShowData()
Try
Connection.Open()
Catch ex As Exception
MessageBox.Show("Connection failed !!!" & vbCrLf & "Please check that the server is ready !!!", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Try
MySQLCMD.CommandType = CommandType.Text
MySQLCMD.CommandText = "SELECT data1,data2 FROM " & Table_Name & " WHERE cid=" & cid.Text & ""
MySQLDA = New MySqlDataAdapter(MySQLCMD.CommandText, Connection)
DT = New DataTable
Dati = MySQLDA.Fill(DT)
If Dati > 0 Then
DataGridView1.DataSource = Nothing
DataGridView1.DataSource = DT
DataGridView1.DefaultCellStyle.ForeColor = Color.Black
DataGridView1.ClearSelection()
Else
DataGridView1.DataSource = DT
End If
Catch ex As Exception
MsgBox("Connection Error !!!" & vbCr & ex.Message, MsgBoxStyle.Critical, "Error Message")
Connection.Close()
Return
End Try
DT = Nothing
Connection.Close()
Save/Update Button Click
Dim mstream As New System.IO.MemoryStream()
If StatusInput = "Save" Then
Try
Connection.Open()
Catch ex As Exception
MessageBox.Show("Connection Failed" & vbCrLf & "Check internet connection !!!", "No connection", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Try
MySQLCMD = New MySqlCommand
With MySQLCMD
.CommandText = "INSERT INTO " & Table_Name & " (data1, data2) VALUES (#data1, #data2)"
.Connection = Connection
.Parameters.AddWithValue("#data1", textbox1.Text)
.Parameters.AddWithValue("#data2", textbox2.Text)
.ExecuteNonQuery()
End With
MsgBox("Data saved successfully", MsgBoxStyle.Information, "Information")
ClearInputUpdateData()
Catch ex As Exception
MsgBox("Data failed to save !!!" & vbCr & ex.Message, MsgBoxStyle.Critical, "Error Message")
Connection.Close()
Return
End Try
Connection.Close()
Else
Try
Connection.Open()
Catch ex As Exception
MessageBox.Show("Connection failed !!!" & vbCrLf & "Please check that the server is ready !!!", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Try
MySQLCMD = New MySqlCommand
With MySQLCMD
.CommandText = "UPDATE " & Table_Name & " SET `data1` = #data1, `data2` = #data2 WHERE id=#id"
.Connection = Connection
.Parameters.AddWithValue("#data1", textbox1.Text)
.Parameters.AddWithValue("#data2", textbox2.Text)
.Parameters.AddWithValue("#id", id.Text)
.ExecuteNonQuery()
End With
MsgBox("Data updated successfully", MsgBoxStyle.Information, "Information")
ButtonSave.Text = "Save"
DatePicker1.Enabled = True
ClearInputUpdateData()
Catch ex As Exception
MsgBox("Data failed to Update !!!" & vbCr & ex.Message, MsgBoxStyle.Critical, "Error Message")
Connection.Close()
Return
End Try
Connection.Close()
StatusInput = "Save"
End If
ShowData()
Edit Button Click
If DataGridView1.RowCount = 1 Then
textbox1.Text = data1Ram
textbox2.Text = data2Ram
ButtonSave.Text = "Update"
StatusInput = "Update"
Return
End If
DataGridView1 CellMouseDown
Try
If AllCellsSelected(DataGridView1) = False Then
If e.Button = MouseButtons.Left Then
DataGridView1.CurrentCell = DataGridView1(e.ColumnIndex, e.RowIndex)
Dim i As Integer
With DataGridView1
If e.RowIndex >= 0 Then
i = .CurrentRow.Index
LoadImagesStr = True
data1Ram = .Rows(i).Cells("data1").Value.ToString
data2Ram = .Rows(i).Cells("data2").Value.ToString
ShowData()
End If
End With
End If
End If
Catch ex As Exception
Return
End Try
EDIT 1
As the error message explains, this is a command syntax problem.
In fact, I tried replacing this string in ShowData()
"SELECT data1,data2 FROM " & Table_Name & " WHERE cid=" & cid.Text & ""
with this
"SELECT data1,data2 FROM tablename WHERE cid = 10"
and no errors appear.
So I need to figure out how to put the table name and conditions inside the command string
As the error message explains, this is a command syntax problem.
In fact, I tried replacing this string in ShowData()
"SELECT data1,data2 FROM " & Table_Name & " WHERE cid=" & cid.Text & ""
with this
"SELECT data1,data2 FROM tablename WHERE cid = 10"
and no errors appear.
So I need to figure out how to put the table name and conditions inside the command string
Edit
Solved.
Thanks to comments. Connections and Commands need to be declared and disposed in the method where they are used. Do not declare then outside this method.

SqlDataAdapter#Fill: `SelectCommand.connection` property has not been initilized

I am making a Student Management System for our thesis. When I click the login button after I put the username and password, this error shows up in da.Fill(dt):
InvalidOperationException was unhandled
Fill: SelectCommand.connection property has not been initilized.
Here is my code in login button
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
con = New SqlConnection(cs)
Dim username As String = TextBox1.Text
Dim password As String = TextBox2.Text
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ")
da = New SqlDataAdapter(cmd)
dt = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
name = TextBox1.Text
MessageBox.Show("Login Successful", "success!",
MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MsgBox("Invalid Login Information!", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End If
End Sub
End Class
When I click the login button I should get to the home page.
This is the login:
and this is the home:
You have to specify which connection to use in your command.
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ", con)
Please note, you are concatenating string to build your SQL Query. This is VERY unsecure. This lead to SQL Injection! Please at least double quote in string variable, and check int variable that are variable. But I strongly suggest you to use parametrized variable (See sp_executeSql).
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text.replace("'", "''") + "'and password'" + TextBox2.Text.replace("'", "''") + "' ", con)
Comments and explanations in-line.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
Dim Exists As Boolean
'The Using block ensures that your database objects are closed and disposed
'even if there is an error.
Using con = New SqlConnection(cs)
'All you need to know is if the record exists. You do not need to return
'the values you just entered.
'Pass the connection to the constructor of the command
Using cmd = New SqlCommand("If Exists (Select username, password From login Where
username=#User and password = #Password;", con)
'Use parameters. It not only helps protect your database against SQL Injection but
'simplifies your SQL statement
cmd.Parameters.Add("#User", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = TextBox2.Text
'You do not need a data adapter or data table for this
'Use execute scalar when you are returning a single value
con.Open()
Exists = CBool(cmd.ExecuteScalar)
End Using
End Using
If Exists Then
Name = TextBox1.Text
MessageBox.Show("Login Successful", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MessageBox.Show("Invalid Login Information!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
EDIT
Never store passwords as plain text.

Searching a database for a string and taking relevant information VB

I want to be able to search my database for a product name or product ID number and then load any relevant information regarding the product into text boxes.
My current code has no build errors however it doesn't seem to return any information. Its probably just something small and I'm being an idiot but I cant fathom the problem.
Private Sub btnSearchProducts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearchProducts.Click
ds.Clear()
If txtProductName.Text = "" And txtProductID.Text = "" Then
MessageBox.Show("Please enter either a Product ID or Product Name..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
If txtProductID.Text <> "" Then
For Each ch As Char In txtProductID.Text
If Not Char.IsDigit(ch) Then
txtProductID.Clear()
MsgBox("Please enter a valid Product ID. Only integers are a valid input", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Next
End If
' Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Computing Project\Database1.accdb"
Dim Command As New OleDb.OleDbCommand
Try
Dim sql As String = "SELECT * FROM tbl_stock WHERE S_ID = '" & txtProductID.Text & "'OR S_ProductName = '" & txtProductName.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Stock")
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
txtProductID.Text = CInt(ds.Tables("Stock").Rows(0).Item(0))
txtProductName.Text = ds.Tables("Stock").Rows(0).Item(3)
txtProductPrice.Text = "£" & CDec(ds.Tables("Stock").Rows(0).Item(2))
Else
If txtProductID.Text <> "" Then
MsgBox("Sorry, " & txtProductID.Text & " is not a valid Product ID", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtProductID.Text = ""
End If
If txtProductName.Text <> "" Then
MsgBox("Sorry, " & txtProductName.Text & " is not a valid Product Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtProductName.Text = ""
End If
End If
Catch ex As Exception
End Try
End If
End Sub
Any help is much appreciated
A few thoughts about this, that might point you to the right direction.
It looks that you are combining two different logical processes. Filling a dataset, then trying to read from the same query again. Rather than calling out to "read" for your if statement. Look for the count of rows on ds.Tables[0] that might resolve the immediate issue.
Please have a look at parameterized SQL Queries, building from raw user entry allows for malicious actions and all efforts should be taken to avoid it if you can.
Looking at your query, you are looking for an exact match on ID, or name. You might switch to a LIKE operation on the name rather than an exact match.

VB.net not working with SQL

I have a problem that is eating my brains out.
I have a project with 2 forms : 1 that extracts the data from my database ( name and surname) and another one that checks out if the user input of the user is correct (matching name and surname) . The code for the 1'st form is :
http://pastebin.com/rg5GMuu6
The code for the second is pasted here
I have no idea whatsoever how to repair this error. I've heard something about some sort of an adapter or something......Help
Ty in advance
I am using MySQL (Easy PHP);
Uploading some pics:
The first form is working without any problems, the second one gives me this error
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost; Database = users; Uid = root; Pwd = password")
strQuery = "SELECT users.name, users.surname FROM users" & _
" WHERE users.name = #Username AND users.surname = #UserPassword"
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#Username ", TextBox1.Text)
SQLCmd.Parameters.AddWithValue("#UserPassword", TextBox2.Text)
'Database open
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
Captured all the errors with the debugger
There seems to be odd situations with the .AddWithValue statement. I have found it better to set parameter values with the following two lines of code.
cmd.Parameters.Add(New SqlParameter("#UserName", Data.SqlDbType.NVarChar)).Direction = ParameterDirection.Input
cmd.Parameters("#UserName").Value = textbox1.text'obviously don't need this if it is an Output Param

How do I check if a user has a certain role in their profile?

Good-day,
I need some help. I'm trying to query my MySQL database to see if the currently logged on user to my application has certain rights/role. If the queried value does exist, then I want to enable a certain menu item.
I checked out most of the similar questions as I was typing my question, but they mostly deal with ASP and JSP so that confuses me even further (as I haven't studied those yet). I'm still learning VB.Net and MySQL.
Your help would be greatly appreciated.
Here's my code - what am I not doing right?:
Public Sub checkAccessLevel()
Dim dbConn As New MySqlConnection(String.Format("Server={0};Port={1};Uid={2};Password={3};Database=parts", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password))
Dim dbQuery As String = "SELECT Level FROM users WHERE username = '" & FormLogin.TextBoxUsername.Text & "'"
Dim dbAdapter As New MySqlDataAdapter(dbQuery, dbConn)
Dim dbData As MySqlDataReader
Try
dbConn.Open()
dbData = dbAdapter.SelectCommand.ExecuteReader
dbData.Read()
While dbData.Read
Select Case UCase(dbData(0).ToString)
Case Is = "Admin"
TSMenuItemOptions.Enabled = True
Case Is = "Manager"
TSMenuItemOptions.Enabled = True
Case Is = "User"
TSMenuItemOptions.Enabled = False
End Select
End While
dbData.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
Finally
dbAdapter.Dispose()
dbConn.Close()
End Try
End Sub
I managed to resolve my own question as follows;
By modifying the Select Case statement....
ORIGINAL (Incorrect):
Select Case UCase(dbData(0).ToString)
MODIFIED (Correct):
Select Case dbData(0).ToString