Grab a Column in MySQL in VB.NET - mysql

I have just learned MySQL in VB.NET, but I am having a complication..
When I grab a SELECT Query, I want to get - lets say the 'username' column in each row it receives. How would I do that?
MySQL.CommandText = "SELECT * FROM online"
MySQL.ExecuteNonQuery()
Label1.Text = 'usernamehere'
Thanks :)

Public Sub CreateMySqlDataReader(mySelectQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetString(0))
End While
Finally
myReader.Close
myConnection.Close
End Try
End Sub
Found on: http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html#connector-net-examples-mysqlcommand-executereader
Also as a bonus. If you are going to throw in some parameters in that query I would suggest you look into prepared statements.

Related

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

Loop through Database table and get all values of each record in turn

I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub

Get first entry from MySQL database in VB

Could you please help me? I just want to take the first row of a table in a mysql database via Visual Basic. I prefer simple code. The only thing i found is using a while, thing that i dont want. Thanks in advance!
Try something like this
Try
Dim sql As String = "SELECT first_row FROM test_table WHERE id = 1"
Dim cmd as OleDbCommand
cmd = New OleDbCommand(sql, Reconnect)
Dim itmReader as SqlDataReader
itmReader = cmd.ExecuteReader
If itmReader.Read Then
Dim firstRowData as String
firstRowData = itmReader.Item("first_row")
MessageBox.Show(firstRowData)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

data reader in vb.net

Please help, how do I make a while loop equivalent of this for loop. So that I could read from one row in the table of mysql database and display it on the combobox in vb.net.
I use this code, but its definitely not useful if there are 3 or more items that are added in the row:
Dim i As Integer
Dim rdr As Odbc.OdbcDataReader
rdr = con.readfrom_drug_type_table()
For i = 0 To 1
If rdr.HasRows = True Then
rdr.Read()
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Next i
I want to read all the data from that the Drug_type row
Please help, thanks
If you want to read only first row than just use
If rdr.Read() Then
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Update
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
' writing to console
End While
Catch
End Try
dr.Close()
myConnection.Close()
#pranay
You don't need the nested loops.
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader()
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
End While
dr.Close()
Finally
myConnection.Close()
End Try

SQL and VISUAL BASIC 2008 Queries

How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.