Need help filling datagrid from MySQL - mysql

I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try

You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).

Related

How properly insert data from dynamic DataTable to MySQL?

Actually i have a method where the user is able to choose data from excel file and choose between some headers name which are set statically and are equals to MySQL columns name in a table, then i just collect that data in a DataTable.
Now i would be able to store that data in MySQL database but which would be the best method to insert that data from a DataTable into MySQL? The rows of DataTable could contain more than 50.000/100.000 items.
That's how the DataTable could look's like (The header is choosen dynamically by the user from a combobox)
So in this Insert method which would be the best way to add that data? Should i just loop throw dataTable items and make multiple inserts?
Private Sub InsertDB()
Dim dataTable = ExcelToDT(TxtUpload.Text, ColumnHeader(PanelColumns, Column))
Dim dbCon As New Odbc.OdbcConnection
Dim conStr As String = "DSN=WRRPT"
dbCon.ConnectionString = conStr
dbCon.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "INSERT INTO ? VALUES ?"
.Connection = dbCon
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
dbCon.Close()
reader = Nothing
cmd = Nothing
End Sub

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

Inserting data from MySQL database into DataGridView

I have a MySQL database with the columns TIME and METHOD, which have about 15,000+ rows of data. I need to get these columns/rows to display on a DataGridView within a vb.net form. I am using the MySql.Data.dll to connect to the database and run my queries. Below is my current code:
Private Sub RetreiveData() Handles Button.click
Dim dt As New DataTable
Dim connectionString As String = "server=ipaddress;database=debugging;user id=root;password=password;port=3307"
Dim connection As MySqlConnection = New MySqlConnection(connectionString)
Try
connection.Open()
Dim sql As String = String.Format("SELECT time, method FROM test1 WHERE custPin='{0}' AND dataID='{1}' ORDER BY TIME;", customerPin, sessionID)
Dim dAdapter As MySqlDataAdapter = New MySqlDataAdapter(Sql, connection)
dAdapter.Fill(dt)
Catch ex As Exception
MessageBox.Show("ERROR: " & ex.Message & Environment.NewLine & ex.StackTrace & Environment.NewLine)
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try
Me.dgvCustomerData.DataSource = dt
connection.Close()
End Sub
Note: "dgvCustomerData" is my DataGridView on my form, and "customerPin"/"sessionID" are retrieved from TextBoxes on my form as well.
I have checked through about 20-30 forum posts that state I should bind my data, or use different styles of data adapters, but none have been able to display my data. I can get it to create the two columns, however, no data is filled in. Any assistance would be very helpful, thanks in advanced.

Get specific row col values from mysql using vb 2012

I have one button retrieve I just want to get the database table "account" value by its row and col and display it in a textbox. I keep on getting errors on the datafill line
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dataset As DataSet
Dim datatable As DataTable
Dim sqlcon As MySqlConnection
Dim dataadapter As MySqlDataAdapter
Dim sqlcommand As MySqlCommand
Dim sql As String
Private Sub retrieve_Click(sender As Object, e As EventArgs) Handles retrieve.Click
sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Sub
End Class
You need to instantiate the dataset that you pass to the Fill method.
....
dataset = new DataSet()
dataadapter.Fill(dataset)
...
Do not forget to close the connection when finished. It is a resource very costly to keep open when you not need it
Using sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataset = new DataSet()
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Using
See the Using Statement
However if you need only one row it is better to refine the query applying a WHERE clause to limit the results returned by the database.
sql = "select * from account WHERE AccountName = #name"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.SelectCommand.Parameters.AddWWithValue("#name", inputNameBox.Text)
dataset = new DataSet()
dataadapter.Fill(dataset, "Account")
if dataset.Tables("Account").Rows.Count > 0 then
TextBox2.Text = dataset.Tables("Account").Rows(0).Item(0).ToString()
End If
this hopefully will return just the row needed

put the contents of the database to a combobox

I am using vb.net and mysql as the database.
I have created a field containing the abbreviations of words. My vb.net form provides a combobox which I want to connect to the field abbreviation. I want to configure the combobox so that when clicked, all the acronyms that exist in the database appear in the combobox.
Any suggestions on how I can get started?
Something like this:
Dim conn As New SqlConnection(connString)
Dim strSQL As String = "SELECT * FROM abbreviations"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "abbreviations")
With ComboBox1
.DataSource = ds.Tables("abbreviations")
.DisplayMember = "abbreviation_name"
.ValueMember = "abbreviation_id"
.SelectedIndex = 0
End With
Should give you the right idea to get started.