MySQL Query Execution with Visual Basic - mysql

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"

Related

Is there away to display the databases of a MySQL server, put it in a combobox, and display it's contents in a datagridview table in VB.Net?

I have a project for school wherein I need to do the above problem, however, our Prog teacher didn't properly fully teach us about mysql and binding it to VB.Net. So I am at a complete loss right now.
I am using Visual Basic.Net on Studio 2019.
Actually this is quite easy in MySql. Normally a connection string would include a database= clause but is this case you want a list of all databases.
My string looks like
Private ConStr As String = "server=localhost;user id=xxx;password=xxx"
Of course you would reference your server. The user id and password would probably need an account with admin privileges.
Private Sub DisplayDatabases()
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand("show databases", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
ComboBox1.DisplayMember = "Database"
ComboBox1.DataSource = dt
End Sub
Private Sub DisplayTables(DB As String)
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand($"use {DB}; show tables", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Sub
Usage:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
DisplayDatabases()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
DisplayTables(ComboBox1.Text)
End Sub
I certainly wouldn't want to be displaying this much info to just any user.
if you are sure about that the server is mySQL you can add the MySql.Data.dll to your project first (MySQL Connector/NET), here is some code to guide you in your project:
Imports MySql.Data.MySqlClient
Public Class Form2
Private Sub Test()
Dim myConnection As MySqlConnection = New MySqlConnection("server=localhost; user id=root; password=yourpassword; database=yourDB; pooling=false;")
Dim strSQL As String = "SELECT * FROM my_users;"
Dim myDataAdapter As MySqlDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
Dim myDataSet As DataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "my_users")
MySQLDataGrid.DataSource = myDataSet
MySQLDataGrid.DataBind()
End Sub
End Class

VB.Net from table(time data type) to label

I have a problem regarding producing report but before that I need to run a code in order for me to create multiple conditions for the next report.
I have here a screenshot of my tbldtr. What I want is the value of am_time_in which has the data type of time will be transferred into a label/textbox/variable. I am using Visual Basic with MySQL.
Here is my code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
checktime()
End Sub
Private Sub checktime()
Dim cn As New MySqlConnection(CnPath)
Dim Sql As String = "SELECT `tbldtr`.`am_time_in` FROM `tbldtr` WHERE `tbldtr`.`id` = '11' AND `tbldtr`.`dtrdate` = '2017-10-16'"
Dim daCmd5 As New MySqlCommand(Sql, cn)
cn.Open()
Dim datinfo As MySqlDataReader = daCmd5.ExecuteReader()
While datinfo.Read()
If IsDBNull(datinfo(0)) = True Then
lblamtimein.Text = ""
Else
lblamtimein.Text = datinfo(0)
End If
End While
cn.Close()
End Sub
End Class
Error here:
The error is occurring on this line -
lblamtimein.Text = datinfo(0)
A timespan needs to be explicitly converted to a string like this -
lblamtimein.Text = datinfo(0).ToString

Passing parameters by value

To all, I am learning Visual Basic and I am currently working on a Windows Application. I have two text box methods (usernameTextBox, passwordTextBox). In which the user will enter data and then hit the submit button (Button1_Click). That method will call connect. What I want to be able to do, is to have the user type-in their username and password. Then it is passed by value, not reference into connect() when it is invoked inside the Button method.
Kind of like an authentication page. Now I have values in connect(FirstName:="JohnDoe", Password:="password") - this is basically for testing MySQL server and for demonstration of what I am trying to attempt.
Imports MySql.Data.MySqlClient
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Public Sub connect(ByVal FirstName As String, ByVal Password As String)
Dim DatabaseName As String = "mysql"
Dim server As String = "10.1.0.0"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, FirstName, Password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName:="JohnDoe", Password:="password")
End Sub
Private Sub SecurePasswordList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub usernameTextBox_TextChanged(sender As Object, e As EventArgs) Handles usernameTextBox.TextChanged
Dim FirstName As String
FirstName = usernameTextBox.Text
End Sub
Private Sub passwordTextBox_TextChanged(sender As Object, e As EventArgs) Handles passwordTextBox.TextChanged
Dim Password As String
Password = passwordTextBox.Text
End Sub
End Class
Change
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName:="JohnDoe", Password:="password")
End Sub
to
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName, Password)
End Sub
but you should ensure that FirstName and Password are initialized AND held as class variables.
Move
Dim FirstName As String
Dim FirstName As String
to be in the class, not the event handling functions (Click etc). Like this:
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Dim FirstName As String
Dim FirstName As String
BUT really you can redo your code like this (as all you want is the Text from the controls):
Imports MySql.Data.MySqlClient
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Public Sub connect(ByVal FirstName As String, ByVal Password As String)
Dim DatabaseName As String = "mysql"
Dim server As String = "10.1.0.0"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, FirstName, Password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(usernameTextBox.Text, passwordTextBox.Text)
End Sub
End Class
I dont think passing by value or reference is the issue here. Do you want the connect function to modify the strings passed into it? I doubt it. So in that case Value or reference is fine. Strings are passed by a copied instance by reference, so in effect they are passed by Value unless you use Byref in the function declaration which will. Every class (int, string, etc) are passed differently in VB by default. You need to check each type to know what it will do if you specify Byval or Byref. String creates a copy of the String if you use Byval, but is actually accessed using the pointer to the newly created String. So it depends how deep you want to dig too

Having issues with pulling data to a listbox, MySQL to VB.Net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;password=Password;database=giordydatabase")
conn.Open()
Dim command As New MySqlCommand("SELECT firstName, lastName FROM student ORDER BY firstName;")
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "student")
Dim dataTable As DataTable = dataSet.Tables("student")
For Each row As DataTable In dataTable.Rows
Dim newStudent As New Student
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
Dim mainStudentList As Object = Nothing
mainStudentList.add(newStudent)
lstStudents.item.add(newStudent.nameConcat)(newStudent.strFirstName, strLastName)
Next
Catch ex As Exception
MsgBox("Error " & ex.ToString())
Finally
conn.Close()
End Try
End Sub
I have an issue as I would like to connect my database to the listbox, also would like it to pull data only the first name and last name data and combine the two to create a name for a list for students to select themselves. But the code above isn't allowing me to do this.
Note the list box is only there for user selection and once they select themselves the they can use the application under the name they selected.
Your problem seems to be the fact that you are setting your main students list to type object and as nothing...
Try to move this line
Dim mainStudentList As Object = Nothing
out of where it is nested and move it so that it is the FIRST line in your code block...
Also instead of what you got currently in that line, change it to...
Dim mainStudentList As Generic.List(Of Student)
Finally change this line...
lstStudents.item.add(newStudent.nameConcat)(newStudent.strFirstName, strLastName)
to ...
lstStudents.item.add(Trim(newStudent.strFirstName) & " " & Trim(newStudent.strLastName))
Try that and see what happens, Good luck.

Sending results from a class to other class

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