VB - MySql 从数据库中选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18801038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB - MySql select from a database
提问by WireCoder
This is how my form looks like - image.
这就是我的表单的样子 -图像。
When form loads, I would like to retrieve the player data whose username
is in the Label1
, so I could display its points
in the Label2
.
当加载窗体时,我想获取玩家数据,其username
是在Label1
,所以我可以显示其points
在Label2
。
Here's my code so far:
到目前为止,这是我的代码:
Dim conn As MySqlConnection
conn = New MySqlConnection("server=REMOVED;Port=REMOVED; user id=REMOVED; password=REMOVED; database=REMOVED")
Dim username As Boolean = True
conn.Open()
Dim sqlquery As String = "SELECT Name FROM NewTable WERE Name='" & My.Settings.Name & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
Label1.Text = data(1).ToString
Label2.Text = data(3).ToString
End While
data.Close()
conn.Close()
Any help would be much appreciated.
任何帮助将非常感激。
采纳答案by John Woo
You should parameterized your query to avoid sql injection, Using
for proper object disposal, Try-Catch
block to handle the exception properly.
您应该参数化您的查询以避免 sql 注入, Using
为了正确处理对象,请Try-Catch
阻止以正确处理异常。
Dim connString As String = "server=REMOVED;Port=REMOVED; user id=REMOVED; password=REMOVED; database=REMOVED"
Dim sqlQuery As String = "SELECT Name, Points FROM NewTable WHERE Name = @uname"
Using sqlConn As New MySqlConnection(connString)
Using sqlComm As New MySqlCommand()
With sqlComm
.Connection = sqlConn
.Commandtext = sqlQuery
.CommandType = CommandType.Text
.Parameters.AddWithValue("@uname", My.Settings.Name)
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
Label1.Text = sqlReader("Name").ToString()
Label2.Text = sqlReader("Points").ToString()
End While
Catch ex As MySQLException
' add your exception here '
End Try
End Using
End Using