从mysql中选择放入变量VB.NET
我正在尝试使用VB.NET从MySQL数据库中选择数据从mysql中选择放入变量VB.NET,mysql,vb.net,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 N
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 & "'"
但我不知道如何将所选查询放入变量,
有人能帮我吗 您可以使用以下ExecuteScalar方法
object nama_studentObj = cmd.ExecuteScalar()
if nama_studentObj != null then
string nama_student= nama_studentObj .ToString()
注:
最好在调用数据库时使用参数,如下所示
cmd.CommandText = "SELCECT nama_student FROM student where Id_student = @Id_student"
然后您必须将参数添加为
cmd.Parameters.AddWithValue("Id_student", id )
您可以将其放入
数据集中
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
通过上述命令,您的数据将存储在数据集中
要使用的示例:
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以了解更多信息:
数据集:
数据表:
数据行:
注:
正如@joelcoehoorn所提到的,尝试查看命令参数
使用数据读取器,您可以将查询结果分配给变量StrVar,这会很方便。我之所以使用GetString,是因为我假设它是字符串类型,而GetValue是integer。值“1”表示要传递给变量的列
让我知道这是否有效。干杯..快乐编码..您的代码易受sql注入攻击。使用这样的字符串连接将值替换为sql查询是不合适的。哦,是吗?你对此有什么建议吗?谷歌“参数化查询”。学习它们。使用它们。感谢您的帮助,但我认为手动连接到MySQL会使味道有所不同没有“手动连接到MySQL”,连接到DB的方式取决于您的需要。如果你觉得读一本书对你更好,那就用它吧。不要喜欢“AddWithValue”。它必须推断sql类型。有时它会出错,宁愿使用nvarchar而不是varchar、nchar或char,这可能会中断索引的使用并强制表中的每一行进行转换,从而导致糟糕的性能。
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
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