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
Related
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.
I want to connect my MySQL to my VB.net.
I am only using Login Form.
I have given the code but the code gives me this error message: Connection must be valid and open
This is my code:
Imports MySql.Data.MySqlClient
Public Class Login
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
Command = New MySqlCommand
Reader = Command.ExecuteReader
Dim count As Integer
count = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Correct !")
ElseIf count > 1 Then
MessageBox.Show("Duplicate !")
Else
MessageBox.Show("Not Correct !")
End If
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
Can anyone help me to fix that? Thanks.
To associate your Query and Command with the connection you need to do this:
Command = New MySqlCommand(Query, MysqlConn)
You can then perform operations to retrieve the data you need.
At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion
I get an error when I try to connect to my database.
What I want to do is to check if I have on the same row from my DataBase a name and a surname
ex. Id_ 1 Michael Dawn
I have 2 textboxes and If they include:
Textbox1 - Michael
Textbox2 - Dawn
Then it's a positive match
I get an error :
Need some help with this one guys, thanks
Here is my code
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
'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" & _
"WHERE users.name = '" + TextBox1.Text + "'AND password = '" + TextBox2.Text + "'"
SQLCmd = New MySqlCommand(strQuery, dbCon)
'Database open
Try
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
I am running the following code (part of it) to connect to PHPmyadmin DB
Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlConnection.ConnectionString = ServerString
Try
If SqlConnection.State = ConnectionState.Closed Then
SqlConnection.Open()
MsgBox("Successfully connected to MySQL DB")
Else
SqlConnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatment As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatment
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
MsgBox("Succesfully Added!")
SqlConnection.Dispose()
End Sub
However the .ExecuteNonQuery() is giving me huge headaches in terms of errors and problems. It uploads the data but, it can only do it once (one upload) before, it returns an error.
When I remove the .ExecuteNonQuery() no data gets uploaded? So I guess it is necessary.
Here is the code im uploading (part of it)
sql = "INSERT INTO students(student_id, title, initial, surname,
street, city, pcode, country ) VALUES ('" & strStudent & "', '"
& vtital & "', '" & vinital & "', '" & vsurname & "', '" & vstreet
& "', '" & vcity & "', '" & vpcode & "', '" & vcountry & "' )"
SaveNames(sql)
Hope my question makes sense and that I can get the message across
There are some errors in your approach to save this data that could lead to your problem.
The first problem is that code doesn't use a parameterized query. This is a security concern (Sql Injection) but also a simple logical problem. If you concatenate strings to build a sql query you have a problem with strings that contains characters with a special meaning for the database sql engine. What if one of your strings contains a single quote? It will be seen as the end of the string with the remainder of your text as invalid sql.
The second problem is the lacking of open/close/dispose of the MySqlConnection also in case of exceptions. This is resolved by using the Using Statement.
So I would rewrite your method as
Public SaveNames(ByRef SQLStatment As String, List(Of MySqlParameter) parameters) As Integer
Using con = new MySqlConnection(... put here the connection string...)
Using cmd = New MySqlCommand(SQLStatment, con)
if parameters.Count > 0 Then
cmd.Parameters.AddRange(parameters.ToArray())
End If
return cmd.ExecuteNonQuery()
End Using
End Using
End Function
And call it with code like this
sql = "INSERT INTO students(student_id, title, initial, surname," & _
"street, city, pcode, country ) VALUES (#id,#title,#init,#sur," & _
"#street,#city,#pcode,#country)"
Dim ps = New List(Of MySqlParameters)()
Dim p = new MySqlParameter("#id", MySqlDbType.Int32).Value = Convert.ToInt32(strStudent)
ps.Add(p)
p = new MySqlParameter("#title", MySqlDbType.VarChar).Value = vtital
ps.Add(p)
.. and so on for the other parameters.
.. respecting the actual datatype on the database table
.....
SaveNames(sql, ps)
Try this ...
cmd = New MySqlCommand( sqlstatement, conn)
conn.open()
cmd.ExecuteNonQuery()
conn.Close()
And as I suggested you .. use parameterized
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.