Sending results from a class to other class - mysql

How can i send results from a class to other class, the results it from my mysql results.
example first class it databaseConnection and i want to send the result from select method to other class.
Here my code:
Dim data As ArrayList
Public Function selectAll() As ArrayList
Dim mySelectQuery As String = "SELECT * FROM users"
Dim myConnection As New MySqlConnection(connectionString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
' Always call Read before accessing data.
data = myReader
' always call Close when done reading.
myReader.Close()
' Close the connection when done with it.
myConnection.Close()
End Function
i updated a code to look more clear
and receiver Method look like this.
Private Sub home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
db = New db()
Dim r = db.selectAll()
MsgBox("It work" & db.selectAll().ToString())
End Sub

You can do this numerous ways.
However, i would probably output the results to a variable in the first function. Then simply access the variable as needed from the second.
Example:
in first method:
Dim list As New List(Of String)
While myReader.Read()
list.add(myreader.GetString(0))
End While
second:
Dim listTransfer as list(Of String)
Foreach ele as String in classname.list ' Replace classname '
listTransfer.add(ele)
Next

Related

Adding a record in Datagridview Row in Vb.net

Hello I have Datagridview in my vb.net form and i want to display the data from the MySQL table to the Datagridview (Dgv) of Vb.net but the problem is when i update or delete an record in Dgv the current record that i fetch is adding more display of the current record. I write this code like this because I'm going to add more function on it, I know i can do this using MySqlDataAdapter and DataSet then fill the datagridview of this code but i use this to add more function, for now how can i update/delete an record without adding more rows that i currently fetch. or doubling the row's
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
Dim row() As String
row = new String() {empId, empName, empAddress}
DataGridView1.Rows.Add(row)
End While
reader.close()
cmd.close()
I know the problem is in Rows.Add
Added:
Currently the function of this is to display the data and when event or button was click this Sub will be called again. with out adding more display.
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
'before adding new row in datagridview add this code
DataGridView1.Rows.clear();
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
so that it will remove the old value of the row and then add the new value in the database
This should do what you want. You can easily select from sql server to datagridview, change data, and pass change from datagridview to sql server.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source='your_server';Initial Catalog='your_database';Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Error while using MysqlDataAdapter

I was following a tutorial on the internet ( link ) to create a a picture gallery. I got it all working, but i changed:
Private Sub CreateGallery()
i = 0
RemoveControls()
If Directorypath IsNot Nothing Then
Dim di As New IO.DirectoryInfo(Directorypath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.jpg").Concat(di.GetFiles("*.bmp")).Concat(di.GetFiles("*.png")).Concat(di.GetFiles("*.gif")).ToArray
Dim dra As IO.FileInfo
For Each dra In diar1
DrawPictureBox(dra.FullName, dra.Name)
Next
End If
End Sub
to:
Private Sub CreateGallery()
Dim table = New DataTable
Using Connection = New MySqlConnection("Server=localhost;User Id=root;Password=barra;Database=pap")
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
da.Fill(table)
End Using
End Using
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Try
Dim bytes() As Byte
bytes = (row("imagem"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("titulo"))
Catch ex As Exception
End Try
Next
End Sub
It was working fine, the way i wanted, when i tried to do it on another project it gives me an error on 'MySqlDataAdapter':
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
the erros says : Overload resolution failed because no accessible 'New' can be called with these arguments
I tried almost everything i can't make it work.
convert your function as class and call :
dim new_creator as yourclass
...
Try This
Private Sub CreateGallery()
Dim table As New DataTable
Dim Conn As New SqlConnection
Conn = New SqlConnection("Initial Catalog=<DataBase>;User ID=sa;password=<password>;Data Source=<ServerName>"")
Dim com As String = ""
com = "SELECT * FROM Table "
Dim getComm As New SqlDataAdapter(com, Conn)
getComm.Fill(table)
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Dim bytes() As Byte
bytes = (row("Imagee"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("Bro_Path"))
End Sub
and change ByVal _filename As MemoryStream,
Private Sub DrawPictureBox(ByVal _filename As MemoryStream, ByVal _displayname As String)

MySQL Query Execution with Visual Basic

I am attempting to make a connection to MySQL server, take input from a text box, the use the information to run query and store it in a listbox.
To go even further I would like to and make the listbox update as I type in the text box.
Whenever I run run the vb nothing populates. I even tried changing the query to something basic, select * from securePasswordList.users; And I can't get anything to populate.
Any suggestions or criticism? THanks! Still learning quite a bit about VB...and a long ways to go.
Imports MySql.Data.MySqlClient
Public Class Reveal
Public Property MyDataClass As SecurePasswordList
Dim lastNameInput As String
Dim firstNameInput As String
Dim connStr As String = "server=0.0.0.0;user=johndoe;database=securePasswordList;port=3306;password=password;"
Dim conn As New MySqlConnection(connStr)
Dim SQL As String = "select password from securePasswordList.users where LAST_NAME like ' " & lastNameInput & "%'"
Dim cmd As MySqlCommand = New MySqlCommand(SQL, conn)
Private Sub Reveal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub firstName_TextChanged(sender As Object, e As EventArgs) Handles lastNameTextBox.TextChanged
lastNameInput = lastNameTextBox.Text
listBox.Items.Add(cmd)
End Sub
Private Sub lastName_TextChanged(sender As Object, e As EventArgs) Handles firstNameTextBox.TextChanged
firstNameInput = firstNameTextBox.Text
End Sub
Private Sub listBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles listBox.SelectedIndexChanged
End Sub
End Class
One of your issues is that you are not actually executing the MySqlCommand anywhere. Also, I would like to point you to this link, since you have a potential security issue in your current code in the way you build your select-string.
Here is an example of how you could retrieve a password:
Private Function RetrievePassword(ByVal lastName As String) As String
Using conn As New MySqlConnection(connStr)
Using comm As New MySqlCommand(query, conn)
comm.Parameters.AddWithValue("#LastName", lastName & "%'")
Dim result As Object = comm.ExecuteScalar()
If result Is Nothing Then
handle as you like...
End If
Return result.ToString
End Using
End Using
End Function
query would contain a placeholder for the parameter like so:
Private Const query As String =
"select password from securePasswordList.users where LAST_NAME like #LastName"

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

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

when i try to select an item in the ListView that has no image in my database this error shows Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. i tried to put up some code like isDBNull or DBNull but it's applicable.
here's my code:
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
Dim Sql As String = "select * from candidate where idn='" & LvPeople.SelectedItems(0).Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
End If
End Sub
End Class
the error points here:
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
i really have no idea what to put here. just a newbie here.
Since it is possible that there is no image data previously saved for a row, you need to test for DBNull before trying to use it:
If IsDBNull(dr("photo")) = False Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
Else
' maybe display a "no Photo Available" stock image
End If
Note that this DBNull test is different than the one Steve is using. IsDBNull is a language function while the one he is using is a method of the DataReader object, which is also why there are different requirements. Yet a third way would be to compare it to System.DbNull:
If DBNull.Value.Equals(dr("photo")) = False Then
...
End If
Use the DataReader method IsDBNull, but this method requires the position of the field in the IDataRecord used by the reader, so you need to call also GetOrdinal with the name of the field to check
(Links point to the Sql Server version but they are the same for MySql)
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "...."
Dim Sql As String = "select * from candidate where idn=#id"
Using conn = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(Sql, conn)
conn.Open()
cmd.Parameters.AddWithValue("#id", LvPeople.SelectedItems(0).Text)
Using dr = cmd.ExecuteReader()
if dr.Read() Then
if Not dr.IsDbNull(dr.GetOrdinal("photo")) Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
End If
End If
End Using
End Using
End Using
End If
End Sub