Check username and password in asp.net - mysql

I tried a lot, but giving the same problem again and again.
When i am entering correct username and password , "if" block and "catch" block ,both are getting executed at the same time. However ,it is not the case with "else" block.
Here is my code.
Try
conn = New SqlConnection
conn.ConnectionString = "Data Source=hp-hp;Initial Catalog=student;User ID=sa;pwd=student"
conn.Open()
comm = New SqlCommand
comm.Connection = conn
Dim sql As String = "SELECT * FROM intern WHERE username='" & TextBox1.Text & "' AND password = '" & TextBox2.Text & "'"
comm.CommandText = sql
reader = comm.ExecuteReader
If reader.Read() Then
Response.Redirect("Register.aspx")
comm.EndExecuteReader(reader)
conn.Close()
'Response.Redirect("Register.aspx")
Else
' If user enter wrong username and password combination
' Throw an error message
MsgBox("Username and Password do not match..")
'Clear all fields
TextBox1.Text = ""
TextBox2.Text = ""
'Focus on Username field
TextBox1.Focus()
End If
Catch ex As Exception
MsgBox("Failed to connect to Database..")
End Try
Thanks.

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.

Duplicate Entry in Vbnet SQL

I have been entering the same username, but it is still saving to DB. What's wrong with my code?
sql = "INSERT INTO testing_mysql_vb(id,user_name) VALUES(NULL,'" & TextBox1.Text & "')"
Try
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
If dbread.HasRows Then
sql = "select from testing_mysql_vb where user_name = '" & TextBox1.Text & "'"
MsgBox("Duplicate record!")
End If
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
dbread.Close()
Exit Sub
End Try
MsgBox("The User Name was saved.")
TextBox1.Text = ""
What I can see that there might be any of two issues:
The username is not primary key or unique constraint, hence its
allowing to save. OR
You are first inserting into DB and then checking whether that username exist into DB or not. It should be other way round.

Mysql won't connect to program VB.net

I have installed the mysql and connector but for some reason it won't connect to the database! I am trying to make a simple login system obviously with a mysql database I created with 000webhost.com but every time I try to log in I get the error of not being able to establish connection?
here is my code:
If username.Text = "" Or password.Text = "" Then
MsgBox("Please enter a Username and Password")
Else
'Connect to Database
Dim connect As New MySqlConnection("server=host;user id=dbuser;Password=pass;database=dbname")
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error couldn't establish a connection to the database")
End Try
'SQL Query to Get the Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquery = "Select * From User where username = '" + username.Text + "' And password = '" + password.Text + "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = connect
myCommand.CommandText = sqlquery
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
MsgBox("UserName N Password is accepted!")
End If
End If

Why do I keep getting this mysql error?

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.