嗨stackoverflow人! 我最近开发了一个简单的vb.net程序,它连接到一个mysql数据库,用于注册和登录具有给定凭据的用户。我已经使用此代码注册我的用户,但我一直得到错误(在代码下面)
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
在打开其他数据之前我已经关闭了所有的datareader,所以我不明白为什么这不起作用...
错误:
感谢您对此话题的任何帮助! 谢谢 Rodit
答案 0 :(得分:0)
我会在所有一次性对象周围使用using语句,以确保它们在不再需要时释放每个对连接的引用,但是看看你的代码,我认为你根本不需要datareaders,因为您可以使用命令解决问题
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
当然我已经用参数化查询替换了你的字符串连接。这是避免Sql Injection
的重要事项我已经用可以与命令ExecuteScalar一起使用的标量操作替换了检查用户存在的查询。此外,在第一个查询中,您似乎尝试插入带有空字符串的字段ID。我认为第一个字段(ID)是一个自动编号字段,在这种情况下,您不会将其添加到插入查询中,也不会传递任何值,因为数据库将为您计算该字段。