Display an error if row already exists in insert data into SQL Server database using vb 2010 - mysql

I have written a program to connect to SQL Server and insert data.
When I insert data into database with same StrUserID in SQL Server, it inserted data a second time, without an error Like that image in sql..
I need to ensure that data is only inserted into the database once, and if a row with the same StrUserID already exists, I need to display a message telling him "such a user name already exists".
Like that photo...
This is my code to insert data into database..
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
My second problem: when user create/insert data into sql I need to make password row change to MD5 not a normal password like the first photo in the first row...
Imports System.Data.SqlClient
Public Class Form2
Public mysqlconn As SqlConnection
Public command As SqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
mysqlconn = New SqlConnection
mysqlconn.ConnectionString =
"Data Source=MY-PC\SQLEXPRESS; initial catalog=SRO_VT_ACCOUNT;user id=sa;password=123"
Dim reader As SqlDataReader
Try
mysqlconn.Open()
Dim Query As String
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
command = New SqlCommand(Query, mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Done")
mysqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

1 Build a unique constraint and handle the appropriate exception:
ALTER TABLE TB_User ADD CONSTRAINT UQ_USER_ID UNIQUE (StrUserID)
https://msdn.microsoft.com/en-us/library/ms190024(v=sql.120).aspx
2 Try HASBYTES function:
insert ...
values (:UserID, HASHBYTES('MD5', pwd))
https://msdn.microsoft.com/ru-ru/library/ms174415(v=sql.120).aspx

Related

How to connect my ASP.Net login code to MySQL database in VB.Net

I have designed a login with registration web page in ASP.Net using VB.NET but I want the new user to first register his/her details and the details to be stored in a MySQL database.
I have created a database in MySQL. I am failing to connect my Registration form to the database in MySQL.
Can someone assist with the connection code for ASP.Net in VB.Net to MySQL database?
This is the code that i have done but it is giving me errors.
Imports MySql.Data
Imports System.IO
Public Class Registration
Inherits System.Web.UI.Page
Dim strConn = "Server=localhost;database=Login;Uid =root;Pwd=;"
Dim con As New MySqlClient.MySqlConnection
Dim cmd As New MySqlClient.MySqlCommand
Dim da As New MySqlClient.MySqlDataAdapter
Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
Dim User_ID, First_Name, Last_Name, Email, Password As String
User_ID = TxtUserID.Text
First_Name = TxtFacultyName.Text
Last_Name = TxtLastName.Text
First_Name = TxtEmail.Text
First_Name = TxtPassword.Text
Dim cmdtxt As String = Nothing
cmdtxt = "Insert into Login(User_ID, First_Name, Last_Name, Email, Password ) " &
"Values('" & User_ID & "','" & First_Name & "', '" & Last_Name & "','" & Email & "','" & Password & "' ) "
Try
'The connection
con.ConnectionString = strConn
con.Open()
'The OLEDB Command
With cmd
.Connection = con
.CommandType = CommandType.Text
.CommandText = cmdtxt
End With
cmd.ExecuteNonQuery()
MsgBox("Registration Successful", MsgBoxStyle.Information, "Registration")
TxtUserID.Clear()
TxtFirstName.Clear()
TxtLastName.Clear()
TxtEmail.Clear()
TxtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
End Class
As far as the connection string, see https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
Keep all your database objects local so you can be sure they are closed and disposed. Using...End Using blocks take care of this for you. You can pass the connection string directly to the constructor of the Connection. Likewise, you can pass the command text and the connection directly to the constructor of the Command.
Your UserID field should be an auto-number field (identity field) in the database. You do not include an auto-number fields in insert commands. For the other fields, use parameters to avoid Sql injection and make writing the sql statement easier. (no ampersands and double quotes and single quotes.
Open the connection at the last possible moment; right before the .Execute...
Imports MySql.Data.MySqlClient
Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
Dim strSql = "Insert into Login(First_Name, Last_Name, Email, Password ) Values(#FName, #LName, #Email, #Password)"
Try
Using con As New MySqlConnection("Server=localhost;database=Login;Uid =root;Pwd=;"),
cmd As New MySqlCommand(strSql, con)
With cmd.Parameters
.Add("#FName", MySqlDbType.VarChar, 50).Value = TxtFacultyName.Text
.Add("#LName", MySqlDbType.VarChar, 50).Value = TxtLastName.Text
.Add("#Email", MySqlDbType.VarChar, 50).Value = TxtEmail.Text
.Add("#Password", MySqlDbType.VarChar, 50).Value = TxtPassword.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the command and connection
MsgBox("Registration Successful", MsgBoxStyle.Information, "Registration")
TxtUserID.Clear()
TxtFirstName.Clear()
TxtLastName.Clear()
TxtEmail.Clear()
TxtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
Finally, NEVER store passwords as plain text. I will leave it to you to research salting and hashing of passwords and add this to the code.

SQL Connection error 40 000webhost with Visual Basic

I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.

MySQL statement to save password to Database?

I have an SQL statement that saves a username into a MySQL database on phpmyadmin that works like a charm:
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`) VALUES ('" & txtUsername.Text & "')"
However
I also ask for the users password, which I'd like to store as well, so I though this would make sense:
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & txtPasswd.Text & "')"
Unfortunately this code does not work, I get errors about a valid and open connection, or a syntax error in my MySQL syntax. So I was wondering if anyone knew the correct way to store the username and password into my DB?
Here is my FULL vb.net code.
Imports MySql.Data.MySqlClient
Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to DB")
Else
SQLConnection.Close()
MsgBox("Failed to connect to DB")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveAccountInformation(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
If txtPasswd.Text = txtPasswd2.Text Then
MessageBox.Show("Passwords Match!")
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & txtPasswd.Text & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
EDIT 1
#Rahul
I added your SQL Statement to my code and I am given the following error when I input a random username/passwd
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll
Additional information: 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 'test')' at line 1
Look at your SQL INSERT statement, it's missing a , comma in VALUES section
VALUES ('" & txtUsername.Text & txtPasswd.Text & "')
^... Here
Your statement should look like
"INSERT INTO accountinfodb(`Usernames`, `Passwords`)
VALUES ('" & txtUsername.Text & "','" & txtPasswd.Text & "')"
Edit:
I must mentioned that your current code is vulnerable to SQL Injection attack due to the fact that you are passing user input directly as concatenated values. You should rather use SqlParameter and pass those values as parameter instead accordingly. A sample would be
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES (#username, #password)"
cmd.Parameters.AddWithValue("#username", txtUsername.Text.Trim())
cmd.Parameters.AddWithValue("#password", txtPasswd.Text.Trim())

Insert in MySql database DataGrid Values

I want to add to mysql database values which i entered in datagrid view.
To delete currently selected ID i use this code.
Dim reader As MySqlDataReader
Try
SqlConn.Open()
Dim query As String
query = "delete from where id='" & DataGridView1.CurrentRow.Index & "'"
Dim command As New MySqlCommand
command = New MySqlCommand(query, SqlConn)
reader = command.ExecuteReader
MessageBox.Show("Data deleted")
ucitaj()
SqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
SqlConn.Dispose()
End Try
But how to add directly from data grid view. I enter the values on the empty field and when i click add i want to add it . I know to add in mysql database i need to use this query
query = "insert into base (id, Username, password, Link) values(Which ones ?)"
this is just quick and dirty. in fact you should do this parameterized
you just have to select it so currentrow is not nothing
If Not DataGridView1.CurrentRow Is Nothing Then
Dim id As Integer = DataGridView1.CurrentRow.Cells("ID").Value
Dim username As String = DataGridView1.CurrentRow.Cells("username").Value
Dim pw As String = DataGridView1.CurrentRow.Cells("password").Value
Dim link As String = DataGridView1.CurrentRow.Cells("Link").Value
Dim sqlstr As String = "insert into base (id, Username, password, Link) values(" & id & "," & username & "," & pw & "," & link & ")"
'your code
End If

How can I insert records in different columns from multiple textboxes in a MySQL table?

How can I add records from multiple text boxes in a VB.net WinForm, to a remote MySQL database? I want to insert the value in the textboxes (fname, lname) to the corresponding columns in a mySQL table. Only one textbox is visible at a time. The next textbox becomes visible only when the previous one has been submitted. I'm using the following code for entering a single record, but am unable to use it for multiple columns.
Imports MySql.Data.MySqlClient
Public Class Regform
Dim serverstring As String = "server=***;Uid=****;database=****;password=****"
Dim SQLstate As String
Dim firstn As String
Dim SQLconnection As MySqlConnection = New MySqlConnection
Private Sub Regform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLconnection.ConnectionString = serverstring
Try
If SQLconnection.State = ConnectionState.Closed Then
SQLconnection.Open()
MsgBox("Connection Established")
Else
SQLconnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
text2.Text = "Well, Hello " & firstn & "Please give me your last name"
End Sub
Public Sub savename(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("Added")
SQLconnection.Dispose()
End Sub
Private Sub cmdsubmit_Click(sender As Object, e As EventArgs) Handles cmdsubmit.Click
SQLstate = "INSERT INTO users(fname) VALUES('" & fname.Text & "')"
savename(SQLstate)
text1.Visible = False
text2.Visible = True
fname.Visible = False
' lname.visible = True
End Sub
Private Sub fname_TextChanged(sender As Object, e As EventArgs) Handles fname.TextChanged
firstn = fname.Text
End Sub
End Class
Can you store the first name in a variable locally until you have the last name? (you already seem to have Dim firstn As String)
firstn = fname.Text
then use something like:
"INSERT INTO users(fname,lname) VALUES('" & firstn & "','" & lname.Text & "')"
If not using this approach or you for this or other reasons want to select back out the ID of inserted rows so that you can update them then use a technique like this:
Return Last ID (IDENTITY) On Insert row VB.NET MySQL
BTW i would not select back out of DB based on first name alone.. they are not very unique ;)
I would not recommend your approach, or rather I may suggest transferring the data from your first form to your second form (assuming they are not on the same form) before submitting the data to the mysql database
create a global declared variable for both forms
Public indform1 As form1
Public indform2 As form2
when you call the form
indform1 = New form1
indform1.Owner = Me
indform1.MdiParent = Me
indform1.Show()
same with form2 - this will allow you to transfer data more easily.
when you create form2 either create a local declared string
dim fname as new string = indform1.fname.text
and use the variable fname to say "hello...."
once they push your submit button for the second form have it run your insert statement
INSERT INTO users(fname,lname) VALUES('" & fname & "','" & lname.Text & "')
or your other option would be to run an update statement after you receive the last name which I would not recommend because as the other responder stated the first name is not very unique unless you add a unique id to it also.
otherwise if it is going to be on the same form and you are only dealing with object visibility - you can use
INSERT INTO users(fname,lname) VALUES('" & fname.text & "','" & lname.Text & "')
making an object visible=false does not modify the content