5

我正在尝试使用 VB.NET 从 MySQL 数据库中选择数据

Dim conn As New MySqlConnection
    Dim cmd As New MySqlCommand
    conn.ConnectionString = "Server=localhost; user id=root; password=; database=aplikasi_store_testing;"
    cmd.Connection = conn
    conn.Open()

    Dim Number As Integer
    cmd.CommandText = "SELCECT nama_student  FROM student where Id_student ='" & id & "'" 

但我不知道如何将选定的查询放入变量中,有人可以帮助我吗?

4

3 回答 3

7
 Dim StrVar as String
 Dim rd As MySqlDataReader 
 Dim cmd as New MySqlcommand


 cmd.commandtext = "Select student_name from student_table where student_id = @ID"
 cmd.connection = conn
 rd = cmd.ExecuteReader

if rd.read then

    StrVar = rd.GetString(1)

end if
rd.close

使用数据阅读器,您可以将查询结果分配给变量 StrVar,这将派上用场。我使用 GetString 是因为我假设它是字符串类型,而 GetValue 是整数。值“1”表示您要传递给变量的列。

让我知道这个是否奏效。干杯..快乐编码..

于 2013-04-30T15:02:35.560 回答
5

您可以使用 ExecuteScalar 方法如下

object nama_studentObj = cmd.ExecuteScalar()
if nama_studentObj != null then
  string nama_student= nama_studentObj .ToString()

完整的示例代码

    Dim cs As String = "Database=testdb;Data Source=localhost;" _
        & "User Id=testuser;Password=test623"

    Dim stm As String = "SELECT VERSION()"
    Dim version As String
    Dim conn As MySqlConnection

    Try
        conn = New MySqlConnection(cs)
        conn.Open()

        Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)

        version = Convert.ToString(cmd.ExecuteScalar())

        Console.WriteLine("MySQL version: {0}", version)

    Catch ex As MySqlException
        Console.WriteLine("Error: " & ex.ToString())
    Finally
        conn.Close()
    End Try

笔记 :

调用数据库时最好使用参数,如下所示

cmd.CommandText = "SELCECT nama_student  FROM student where Id_student = @Id_student"

那么你必须将参数添加为

cmd.Parameters.AddWithValue("Id_student", id )

如何创建参数化 SQL 查询?我为什么要?

于 2013-04-16T02:54:28.500 回答
2

你可以把它放进DataSet

Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = "Server=localhost; user id=root; password=; database=aplikasi_store_testing;"
cmd.Connection = conn
conn.Open()

Dim id As Integer
cmd.CommandText = "SELECT nama_student  FROM student where Id_student ='" & id & "'" 

Dim da As New MySqlDataAdapter 'DataAdapter can be used to fill DataSet
Dim ds As New DataSet
da.SelectCommand = cmd
da.Fill(ds, "student") 'you can change student with the table name

通过上述命令,您的数据将存储在DataSet.

使用示例:

ds.Tables("student").Rows.Count 'Get the number of rows in the DataTable
ds.Tables("student").Rows(0).Item("nama_student").ToString 'Get first row of the nama_student field

您可以查看 MSDN 以获取更多信息:

数据集:http: //msdn.microsoft.com/en-us/library/system.data.dataset.aspx

数据表:http: //msdn.microsoft.com/en-sg/library/system.data.datatable.aspx

数据行:http : //msdn.microsoft.com/en-sg/library/system.data.datarow.aspx

笔记:

正如@Joel Coehoorn 提到的,尝试查看命令参数http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlparameter.html

于 2013-04-16T03:50:13.010 回答