Get specific row col values from mysql using vb 2012 - mysql

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

Related

How to put two fields of database to one combobox in vb.net?

Private Sub ForgotPasswordPage1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim table2 As New DataTable
Dim cmd As New MySqlCommand
Dim cmd1 As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim da2 As New MySqlDataAdapter
Dim con = New MySqlConnection
con.ConnectionString = "server=127.0.0.1;userid=root;password=;database=pharma"
Try
'we open Connection
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT `security_question_1` from pharma.account_admin where `u_name`='" & Login.u_name.Text & "';"
End With
'declare dt as new datatable
Dim dt As New DataTable
Dim dt2 As New DataTable
With sq
da.SelectCommand = cmd
'it fills the da values into dt
da.Fill(dt)
'dt provides the data surce of combobox
.DataSource = dt
'specify the what to display
.DisplayMember = "security_question_1"
'and the value
.ValueMember = "security_question_1"
End With
With cmd1
.Connection = con
.CommandText = "SELECT `security_question_2` from pharma.account_admin where `u_name`='" & Login.u_name.Text & "';"
End With
With sq
da.SelectCommand = cmd1
'it fills the da values into dt
da.Fill(dt)
'dt provides the data surce of combobox
.DataSource = dt
'specify the what to display
.DisplayMember = "security_question_2"
'and the value
.ValueMember = "security_question_2"
End With
Catch ex As Exception
Here's my code. I want to have security question 1 and security question 2, which are two different fields in my database to be inserted in a combobox.
The most important thing in my code is the use of Parameters. This change will help protect your database from malicious input. I also used an alias for security question 1 and 2. (the As Question in the select command.) Double check the data type of User Name. I guessed at varchar but it could be something else. Change the MySalDbType accordingly. Using DataTable.Load adds the records from the second query to the data table. Actually, I think the two select could be run as a Union. If you are only getting 2 questions back then I would select both questions in one query, use a datareader and add the values to the combo box manually. The Using/End Using statements ensure that objects that implement IDisosable can release their unmanaged resources as soon as posible.
Using cmd As New MySqlCommand
Using da As New MySqlDataAdapter
Using con = New MySqlConnection("server=127.0.0.1;userid=root;password=;database=pharma")
Try
With cmd
.Connection = con
.CommandType = CommandType.Text
.CommandText = "SELECT `security_question_1` As Question from pharma.account_admin where `u_name`= #UserName;"
.Parameters.Add("#UserName", MySqlDbType.VarChar).Value = Login.u_name.Text
End With
Using dt As New DataTable
da.SelectCommand = cmd
da.Fill(dt)
cmd.CommandText = "SELECT `security_question_2` As Question from pharma.account_admin where `u_name`= #UserName;"
con.Open()
Using dr As MySqlDataReader = cmd.ExecuteReader
dt.Load(dr)
con.Close()
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Question"
ComboBox1.ValueMember = "Question"
End Using
End Using
Catch ex As Exception
End Try
End Using
End Using
End Using

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

How to display data in datagrid from mysql in multiple forms?

I have 2 forms, in the first form the datagrid populates with data in mysql. Then to repeat this for my second form I copied the code over and changed all variable names, but when I load the form the datagrid is not populated with mysql data, it doesn't even throw an error. Here is the code I used for my first form and below is for my second form.
This is the code for the second form, where it doesn't work, the code is exactly the same (changed variable names) for the first form.
Second form:
Public Class frmShareholderDetails
Dim connection As New MySqlConnection
Dim myadapter As New MySqlDataAdapter
Dim mycommandbuilder As MySqlCommandBuilder
Dim mycommand As MySqlCommand
Dim datatable As New DataTable
Dim dataset As New DataSet
Dim mydatagridviewprinter As datagridviewprinter
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
'declaring variables
Private Sub frmShareholderDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
connection.ConnectionString =
("Server=localhost;database=ba-solutions;user id=root;password=")
Try
connection.Open()
'opens connection
Catch ex As Exception
MsgBox("Cannot connect to BA-Solutions Database")
End Try
myadapter.SelectCommand = New MySqlCommand
myadapter.SelectCommand.Connection = connection
myadapter.SelectCommand.CommandText = "select * from Shareholder_Details"
'creates adapters
mycommandbuilder = New MySqlCommandBuilder(myadapter)
myadapter.Fill(datatable)
myadapter.SelectCommand.CommandType = CommandType.Text
dataset = New DataSet
myadapter.Fill(dataset, "Shareholder_Details")
rowposition = 0
DGVShareholder.DataSource = dataset.Tables("Shareholder_Details")
'sets datasource
connection.Close()
'close connection
Dim recordsondisplay As Integer
recordsondisplay = DGVShareholder.RowCount
lblRecords.Text = recordsondisplay & " records in database."
End Sub
End Class
Can anyone see where the problem lies? I have been using trial and error, but no solution yet.

Need help filling datagrid from 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).