Select from mysql put into variable VB.NET - mysql

I am trying to Select data from MySQL database using VB.NET
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 & "'"
but i dont know how to put selected query into variable,
anybody can help me ?

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
Using the Data Reader it will let you assign the result of the query to your variable StrVar and this will come in handy. I use GetString because I assume it is a string type and GetValue for integer. The value "1" represent the column you want to pass to your variable.
Let me know if this works. Cheers..Happy Coding..

you can use ExecuteScalar method as below
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
Note :
Better to use parameters when you call database, like below
cmd.CommandText = "SELCECT nama_student FROM student where Id_student = #Id_student"
then you have to add the parameter as
cmd.Parameters.AddWithValue("Id_student", id )
How do I create a parameterized SQL query? Why Should I?

You can put it into 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
From above command, your data will be stored in a DataSet.
Sample to use:
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
You can check MSDN for further information:
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
Note:
As mentioned by #Joel Coehoorn, try to look at Command Parameter http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlparameter.html

Related

Getting all the rows of a MySQL table and putting them in a listbox

I want to get all the rows of table of a MySQL database and store them in a listbox. I am using vb.net. Thanks in advance.
Dim connection As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim Column0 As String
connection.ConnectionString = "Data Source=localhost; Initial Catalog=catalogname; Integrated Security=True; Connection Timeout=3"
Dim query As String = "SELECT * FROM MyDB"
connection.Open()
cmd = New SqlCommand(query, connection)
dr = cmd.ExecuteReader
If dr.Read() Then
Column0 = dr(0)
End If
connection.Close()

vb 2010 mysql insert record operation inserts a blank record but no data is inserted

I am trying to develop a utility in vb 2010, which will store values from Datagridview control to a mysql table
Steps
1) Datagrid cell values are stored in an array
2) Array values are used .AddWithValue() function
Present status: Only a blank record is inserted. Data is missing.
Please refer to following code.
Function insertRec()
'dgExistingProject is datagridview control embedded on the form
Dim ServerString As String = "Server=pnserver;User ID=root;
Password=; Database=prayer_net"
Dim Arr(RCount) As String
Dim SQLConn As MySqlConnection = New MySqlConnection
SQLConn.ConnectionString = ServerString
dim I as Integer
For I = 0 To RCount
Arr(I) = dgExistingProject.Rows(I).Cells(1).Value
Next
Try
Dim dt As Date = DateTime.Now.ToString("yyyy/MM/dd
HH:mm:ss")
Dim projName as Integer=Arr(4)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "INSERT INTO dyn_dwg_register
(file_name,file_location,dwg_description,
project_id,created_by, created_on)" & _
" values (#file_name, #file_location, #dwg_description, #project_id, #created_by, #created_on)"
.CommandType = CommandType.Text
.Connection = SQLConn
.Parameters.AddWithValue("#file_name", Arr(0))
.Parameters.AddWithValue("#file_location", Arr(1))
.Parameters.AddWithValue("#dwg_description", Arr(2))
.Parameters.AddWithValue("#project_id", ProjName)
.Parameters.AddWithValue("#created_by", Arr(4))
.Parameters.AddWithValue("#created_on", dt)
End With
Try
SQLConn.Open()
If SQLConn.State = ConnectionState.Open Then
Dim ID As Integer = sqlCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConn.Close()
End Try
End Using
Catch e As Exception
MsgBox (e.Message.ToString)
End Try
End Function
Rajendra Nadkar
i had written a code in C# where i had to store data from a datagrid to SQL database. I used the following code. I think it will help you.
string sqlquery = "UPDATE TableName set ColumnName1=#param1 where ColumnName2=#param2";
using (OleDbCommand Cmd = new OleDbCommand(sqlQuery, dbCon))
{
Cmd.Parameters.AddWithValue("#param1", Convert.ToDouble(dataGridView1[1, index].Value));
Cmd.Parameters.Add(new OleDbParameter("#param2", OleDbType.VarWChar)).Value = "somevalue";
updateDbCmd.ExecuteNonQuery();
updateDbCmd.Parameters.Clear();
}
Funny, I changed the field name prefix # to ? and things became smooth. In an earlier question in Feb 11, Stelian Matei suggested this edit, though later on Giezel Esteves reversed it. (Original question asked by user1176607 in Feb '10)
I guess I need to refer to documentation more thoroughly. Anyways I am giving the working code here if you or anybody interested in it.
Dim qry As String = "INSERT INTO dyn_dwg_register (`file_name` , `file_location`, `dwg_description`, `project_id`, `created_by`)" & _
" values (?file_name, ?file_location, ?dwg_description, ?project_id, ?created_by)"
Dim sqlCommand As MySqlCommand
sqlCommand = New MySqlCommand(qry, SQLConn)
sqlCommand.CommandType = CommandType.Text
With sqlCommand
.Parameters.AddWithValue("?file_name", Arr(0))
.Parameters.AddWithValue("?file_location", Arr(1))
.Parameters.AddWithValue("?dwg_description", Arr(2))
.Parameters.AddWithValue("?project_id", ProjName)
.Parameters.AddWithValue("?created_by", Arr(2))
End With

How can i display multiple result in a series of textboxs?

I have a problem populating multiple data to multiple textboxes. I've attached a link to the project so that you guys can get the picture.
Thank you so much in advance! I'm no wiz programmer. :)
EDIT: heres the code
` Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; password=dctvmainadmin; database=tmsdctv")
Dim query As String = "SELECT * FROM recordedattendance WHERE empno = '00111' and dateattended = '2014-02-03 Mon'"
Dim reader As MySqlDataReader
Dim result As New System.Data.DataTable
con.Open()
Dim Cmd_Read_Name As New MySqlCommand(query)
Cmd_Read_Name.Connection = con
result.Load(Cmd_Read_Name.ExecuteReader)
With Me
For Each dtrow As DataRow In result.Rows
.lblEmpno.Text = dtrow(0)
.lblDate1.Text = dtrow(1)
.txtTimeIn1.Text = dtrow(2)
.txtTimeOut1.Text = dtrow(3)
Next
con.Close()
End With`
Try Like This:
Specifing textbox lable name like:
lblEmpno1,lblEmpno2,lblEmpno3.., lblDate1,lblDate2,lblDate3....,
txtTimeIn1,txtTimeIn2,txtTimeIn3..., txtTimeOut1,txtTimeOut2,txtTimeOut3....
Dim con As MySqlConnection = New MySqlConnection("data source=localhost;
user id=root; password=dctvmainadmin; database=tmsdctv")
Dim query As String = "SELECT * FROM recordedattendance WHERE empno
= '00111' and dateattended = '2014-02-03 Mon'"
Dim reader As MySqlDataReader
Dim result As New System.Data.DataTable
con.Open()
Dim Cmd_Read_Name As New MySqlCommand(query)
Cmd_Read_Name.Connection = con
result.Load(Cmd_Read_Name.ExecuteReader)
For xi as integer=0 to result.Rows.Count-1
Controls("lblEmpno" & xi+1 &).Text .Text = result.Rows(xi).Item(0)
Controls("lblDate" & xi+1 &).Text = result.Rows(xi).Item(1)
Controls("txtTimeIn" & xi+1 &).Text = result.Rows(xi).Item(2)
Controls("txtTimeOut" & xi+1 &).Text = result.Rows(xi).Item(3)
Next
con.Close()

how to retrieve mysql data in vb.net?

im trying to retrieve mysql data with specific column and show to textbox in vb.net. what should i do in retrieving it?
Dim connect As New MySqlConnection("server=localhost; user id=root; password= ; database=ticketing_system;")
connect.Open()
Dim sqladapter As New MySqlDataAdapter
Dim sqlcmd As New MySqlCommand
Dim dr As MySqlDataReader
Dim dt As New DataTable
sqlcmd = New MySqlCommand("SELECT * complaint WHERE tran_no='" & lbltranno.Text & "'")
**THEN? WHAT SHOULD I DO TO DISPLAY DATA? PLEASE HELP**
connect.Close()
You are simply missing the Execution method. It depends on what kind of result you want. If you only want the first result from the query (first row and first column) then use sqlcmd.ExecuteScalar().
If you want all the results you'll have to load that into a MySqlDataReader using the method sqlcmd.ExecuteReader()
Using ExecuteReader() :
Dim connect As New MySqlConnection("server=localhost; user id=root; password= ; database=ticketing_system;")
connect.Open()
Dim sqladapter As New MySqlDataAdapter
Dim sqlcmd As New MySqlCommand
Dim dr As MySqlDataReader
Dim dt As New DataTable
sqlcmd = New MySqlCommand("SELECT * complaint WHERE tran_no='" & lbltranno.Text & "'")
dr = sqlcmd.ExecuteReader()
dt.Load(dr)
'Useable datatable in dt variable...
connect.Close()
Using ExecuteScalar() :
Dim connect As New MySqlConnection("server=localhost; user id=root; password= ; database=ticketing_system;")
connect.Open()
Dim sqladapter As New MySqlDataAdapter
Dim sqlcmd As New MySqlCommand
Dim dr As String
Dim dt As New DataTable
sqlcmd = New MySqlCommand("SELECT [COLUMN NAME] complaint WHERE tran_no='" & lbltranno.Text & "'")
dr = sqlcmd.ExecuteScalar()
'dr now contains the value of [COLUMN NAME] for the first returned row.
connect.Close()
You can try this:
Dim connString As String = "server=localhost; user id=root; password=[REPLACE WITH PASSWORD] ; database=ticketing_system;"
Dim sqlQuery As String = "SELECT * from complaint WHERE tran_no='" & lbltranno.Text & "'";
Using sqlConn As New MySqlConnection(connString)
Using sqlComm As New MySqlCommand()
With sqlComm
.Commandtext = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
Label1.Text = sqlReader("Name").ToString()
Label2.Text = sqlReader("Points").ToString()
End While
Catch ex As MySQLException
' add your exception here '
End Try
End Using
End Using
Imports System.Data.SqlClient
Public Class Form1
Dim c As New SqlConnection("Data Source=SONY;Initial Catalog=msdb;Integrated Security=True")
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dr As SqlDataReader
Dim ds, ds1 As New DataSet
Private Sub btnsub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsub.Click
Try
ds.Clear()
c.Open()
cmd = New SqlCommand("select Sub_Name from Subject_Detail WHERE Course='" + txtcourse.Text + "'", c)
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Subject_Detail")
Label1.Text = ds.Tables(0).Rows(0).Item(0)
Label2.Text = ds.Tables(0).Rows(1).Item(0)
Label3.Text = ds.Tables(0).Rows(2).Item(0)
Label4.Text = ds.Tables(0).Rows(3).Item(0)
Label5.Text = ds.Tables(0).Rows(4).Item(0)
Label6.Text = ds.Tables(0).Rows(5).Item(0)
Catch ex As Exception
MsgBox(ex.Message)
Finally
c.Close()
End Try
End Sub
End Class
'This code display all subject name from the table into labels.This might be helped.
Try this one, i always use this code, that's why i'm pretty sure that this will work...
Imports MySql.Data
Imports MySql.Data.MySqlClient
Dim connect As New MySqlConnection("server=localhost;uid=root;database=ticketing_system;pwd=;")
connect.Open()
Dim sqlcmd As New MySqlCommand("SELECT * complaint WHERE tran_no='" & lbltranno.Text & "'")
Dim sqladapter As New MySqlDataAdapter(sqlcmd)
Dim dt As New DataTable
sqladapter.Fill(dt)
Datagridview1.Datasource = dt
connect.Close()
Imports MySql.Data
Imports MySql.Data.MySqlClient
Dim dbConnection As New MySqlConnection("server=localhost;uid=youruser;database=yourdb;pwd=password")
try
dbConnection.open
catch ex as exception
debug.print(ex.message)
end try
using Adapter as new mysqldataadapter("select * from yourtable where yourcolumn = 'yourvalue'", dbConnection)
using Table as new datatable
Adapter.fill(Table)
Datagridview.datasource = table
end using
end using
dbConnection.close
Imports MySql.Data.MySqlClient
''--- Data Reader Example
private _cn as New MySqlConnection( _
"data source=server; database=databaseName; user id=username; password=password")
private cmd as new MySqlCommand
private dr as MySqlDataReader
With cmd
.Command = "select Name, Address from Clients"
.CommandType = CommandType.Text
.Connection = cn
End With
cn.Open()
dr = cmd.ExecuteReader
While dr.Read
'' use dr(0) for get Name, and dr(1) to get Address for this example
Console.WriteLine(dr(0) & " - " & dr(1))
Console.WriteLine(dr("Name").ToString() & " - " & dr("Address").ToString())
End While
dr.Close
cn.Close
Dim MysqlConn As MySqlConnection
Dim connectionString As String = "Server=-host-ip-;Database=Mysqldb;Uid=user;Pwd=password"
MysqlConn = New MySqlConnection(connectionString)
Try
Dim Mysqlcmd As New MySqlCommand("SELECT * FROM Mysqldb.table WHERE col='" & Label6.Text & "'", MysqlConn)
Dim dt As New DataTable
Dim Mysqladapter As New MySqlDataAdapter()
MysqlConn.Open()
Mysqladapter.SelectCommand = Mysqlcmd
Mysqladapter.Fill(dt)
DataGridView1.DataSource = dt
MessageBox.Show("Connection to Database has been opened.")
MysqlConn.Close()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
MysqlConn.Dispose()
End Try
The key is to add the connection at the end of the mysql query as in line 6
I used a variation of the code given in this thread with Visual Basic 2015. I found I needed a 2nd argument in the MySqlCommand statement, namely the MySqlConnection variable ("connect" in some of the examples). See thread: Connection must be valid and open VB.Net
Thanks for the help.

Convert MySQL DataSet to String

I want to check if a user is an administrator or user and I want to change the dataset to a string so I can use it in Label1.
I've tried Using 'GetXML' but it comes in a funny format something like 'Administrator', well it's a bit different to that. I want to be able to use the value of the label1.text for other features in my program.
Here is my code:
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim ServerString As String = "server=localhost;user id=root;password=;database=business elements"
SQLConnection.ConnectionString = ServerString
SQLConnection.Open()
Dim ds As New DataSet()
Dim cmd As New MySqlCommand("SELECT Level FROM users WHERE username = '" & UsernameTextBox.Text & "'", SQLConnection)
Dim da As New MySqlDataAdapter(cmd)
da.Fill(ds)
Dim str As String = ds.GetXml
ds.GetXml()
Label1.Text = str
Try this
Dim str As String = ds.Tables(0).Rows(0).Item(0).ToString()