根据vb.net的会员名称从数据库中获取值?

时间:2015-06-12 01:27:24

标签: mysql vb.net

我有一个SQL表,看起来像:

+-------------------+
| id   member   req |
+-------------------+
| 1    Jim      0   |
| 2    Mary     0   |
| 3    Hunter   0   |
+-------------------+

我需要通过Visual Basic 2010中的vb.net应用程序(WinForms)获取某个成员的id

让我们说我想要 Mary id。返回 Mary 的<{1}}的SQL查询是什么?

什么是查询?

-------------------------------------------- ------------------------------------

可能的查询代码:

id是我在数据库中查找以获取成员'My.Settings.username的名称。

id

2 个答案:

答案 0 :(得分:0)

首先,下载MySQL connector

其次,添加对项目的MySQL连接的引用。

第三,导入你将使用许多类的命名空间来减少输入(在.vb文件的顶部):

Imports MySql.Data.MySqlClient

最后在Form的Load事件处理程序(或您希望在标签中显示ID的其他事件处理程序)中:

'Change to your specific connection string.
Dim strConnectionString As String = "Database=YourDatabaseName;Data Source=localhost;User Id=YourUser;Password=YourPassword"

Dim sqlConnection As New MySqlConnection(strConnectionString)

Dim strCommandText = "SELECT id FROM members WHERE member = @Member"

'Assumes that the ID field is an INT type.  Use a Long type if the type is a BIGINT.
Dim intID as Integer

Try

    'Open the connection.
    sqlConnection.Open()

    'Create a command to get the ID.
    Dim sqlCommand As MySqlCommand = New MySqlCommand(strCommandText, sqlConnection)

    'It is always a good idea to use parameters.
    sqlCommand.Parameters.AddWithValue("@Member", My.Settings.username)

    vagueID.Text = Convert.ToString(sqlCommand.ExecuteScalar())

Catch ex As Exception
    'Error handling goes here.
    MsgBox(ex.Message)
Finally
    'Always close the connection!
    sqlConnection.Close()
End Try

答案 1 :(得分:-1)

MySQLCon = New MySqlConnection MySQLCon.ConnectionString = "Database=localhost;Data Source=host;User Id=root;Password=root" Dim READER As MySqlDataReader Dim COMMAND As MySqlCommand Try MySQLCon.Open() Dim SQLID As String = "SELECT id FROM members WHERE member='" & My.Settings.username & "'" COMMAND = New MySqlCommand(SQLID, MySQLCon) READER = COMMAND.ExecuteReader() While READER.Read vagueID.Value2 = READER.GetInt32("id") End While MySQLCon.Close() MySQLCon.Dispose() Catch ex As Exception 'Do Something End Try

相关问题