从mysql中选择放入变量VB.NET

时间:2013-04-16 02:43:56

标签: mysql vb.net

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

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

3 个答案:

答案 0 :(得分: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”表示要传递给变量的列。

如果有效,请告诉我。干杯......快乐的编码......

答案 1 :(得分:5)

你可以使用下面的ExecuteScalar方法

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

Full example code

    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 )

How do I create a parameterized SQL query? Why Should I?

答案 2 :(得分: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

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