我正在尝试使用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 & "'" 

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

===============>>#1 票数: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”表示要传递给变量的列。

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

===============>>#2 票数: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查询? 我为什么要?

===============>>#3 票数: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以获取更多信息:

DataSet: http//msdn.microsoft.com/en-us/library/system.data.dataset.aspx

DataTable: http//msdn.microsoft.com/en-sg/library/system.data.datatable.aspx

DataRow: 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

  ask by Vinra Gunanta Pandia translate from so

未解决问题?本站智能推荐: