Add Multiple Databases in VB.NET - mysql

Is it possible to connect multiple databases to a program?
I added a database, but it was always through the "Data Source Config Wizard". My application deals with one main database, but I need to load information from other databases and add it to the main one (the user will select which database through the OpenFileDialog).
Public Class Form1
Private Sub TblTestBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblTestBindingNavigatorSaveItem.Click
Me.Validate()
Me.TblTestBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TestdbDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestdbDataSet.tblTest' table. You can move, or remove it, as needed.
Me.TblTestTableAdapter.Fill(Me.TestdbDataSet.tblTest)
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim DBConnection As New OleDb.OleDbConnection
'''' Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;"
'Dim dbSource As String = opnFile.ShowDialog()
opnFile.ShowDialog()
Dim ex As String = opnFile.FileName
MessageBox.Show(ex)
Dim dbSource As String = "DataSource=" & ex
MessageBox.Show(dbSource, "Data Source String", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Dim DBDataSet As New DataSet
'''' Dim ds As New DataSet
Dim DBDataAdapter As OleDb.OleDbDataAdapter
'''' Dim da As OleDb.OleDbDataAdapter
DBConnection.ConnectionString = dbProvider & dbSource
'DBDataAdapter = (sql, DBConnection)
End Sub
End Class
Also, can someone explain to me the link in DataAdapter, DataConnection, and the DataSet? From what I see, the DataConnection is just the link that will connect the application to the database. The DataSet is your actual data from the database. So what is the DataAdapter for?
Thanks for any help!

You can add several databases using the Database wizard. You will be missing the binding navigator but you can get this easily by creating a temporary form in your project add the database to this then just copy over the binding navigator before deleting the temp form.

See this thread Display data from access using dataset The use the following.
Try something like this after you load your table into a Dataset
For Each row1 In (From dr As DataRow In yourDataSet.Tables(0).Rows Select dr Where dr("Column_Name").ToString.StartsWith(yourstring)
somestring = row1("Column_Name").ToString

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

retrieve text in my mySql database and put into texbox using ODBC in vb.net

I want to retrieve a question from my db and put it into textbox for security questions but I don't know how. I am using ODBC as connection in vb.net into mysql.
Here is my code
Imports System.Data.Odbc
Public Class forgPass
Dim con As New OdbcConnection("DSN=nohdb")
Dim com As New OdbcCommand
Dim dt As DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.Open()
com = New OdbcCommand("SELECT question1 FROM sec_questions WHERE='admin'", con)
dt = New DataTable
dt.Load(com.ExecuteReader)
ques1.Text = dt.ReadXml
con.Close()
End Sub
End Class
You need to add
Imports MySql.Data.MySqlClient
I am assuming the following
You can insert the correct connection string in the con constructor. See
https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
for reference.
question1 is the name of a field in your database table.
sec_questions is the name of a table in your database.
Replace SomeFieldName with the name of field where admin is
found.
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you even if there is an error.
The user interface is not updated until the database objects are closed and disposed with the End Using.
To retrieve data from the DataTable you can refer to the first row in the Rows collection which is index 0. Then the column name, question1. Since the datatype is unknown until runtime we call .ToString to satisfy Option Strict.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
com As New MySqlCommand("SELECT question1 FROM sec_questions WHERE SomeFieldName ='admin';", con)
con.Open()
dt.Load(com.ExecuteReader)
End Using
ques1.Text = dt.Rows(0)("question1").ToString
End Sub

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"

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.

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.