Duplicate Entry in Vbnet SQL - mysql

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.

Related

MySQL Query Browser Error Data truncated for column

This is my code and I dont know why I'm getting this Error in my visual studio 2013 and my data base is MySQL Query Browser:
"Additional information: ERROR [HY000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.34-community]Data truncated for column 'userid' at row 1"
If a = "New" Then
Dim sqlstring As String
sqlstring = "INSERT into users(username, userid, usertype, remarks)values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & ComboBox1.Text & "','" & TextBox4.Text & "')"
cmd = New Odbc.OdbcCommand(sqlstring, cnn)
cmd.ExecuteNonQuery()
reset()
disable()
btn3()
End If
This is because the total length of the characters you are passing exceeded the length defined by column userid. Aside from that, mysql has its own managed provider called MySqlClient and this is the one you should be using.
A much better way to good practice programming is to paramaterized your query. Example below is at least your good starting point:
Dim connectionString As String = "..your connection string here..."
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.CommandText = "INSERT into users(username, userid, usertype, remarks) VALUES (#username, #userid, #usertype, #remarks)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandType = CommandType.Text
sqlCommand.Parameters.AddWithValue("#username", TextBox1.Text)
sqlCommand.Parameters.AddWithValue("#userid", TextBox2.Text)
sqlCommand.Parameters.AddWithValue("#usertype", ComboBox1.Text)
sqlCommand.Parameters.AddWithValue("#remarks", TextBox4.Text)
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
End Using
End Using

how to detect wrong input from user vb

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.

Check username and password in asp.net

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.

getting the id of record added to mysql db

Hoping someone can help me out with this.
I've made an app linked to a mysql db.
I'm writing details of remote hosts to a database at the minute.
I'm saving remote credentials too, but in a different table.
I have a colomn in my 'credentials' table called 'hosts_linked_id' which i want to contain the id of the parent record in the 'hosts' table.
Here is my code so far...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "')"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & txtname.Text & "','" & txtusername.Text & "','" & encryptedpassword & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
Else
SQLConnection.Close()
End If
Also, here's the 'SaveData' function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("Host has been added")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
What i need to do is get the id of the record created when my first 'INSERT' statement is executed into a variable so i can insert it into the 'credentials' table when my second 'INSERT' statement is executed.
I've googled the hell out of this and tried a few different methods, all without success.
Can anyone help point me in the right direction?
Thanks in advance!!
TL;DR: Need to get the ID of mysql record added when insert statement is executed and drop it into a variable

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.