vb.net mysql combobox show tables - mysql

I am new at programming, and I'm working on a basic VB.NET application that allows the user to select, insert, update, and delete various data tables from MySQL.
The trouble I'm having is, I need to populate a combobox with all the table names from one specific database, so that the user can select which database table to work with. I thought my code would work, but all I'm getting when I run the app is a blank combobox.
Could someone please tell me what's wrong with my code?
Thanks so much in advance!
Code:
Private Sub TableList_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TableList.SelectedIndexChanged
Try
command = New MySqlCommand
dt = New DataTable
adapter = New MySqlDataAdapter
If (conn.State = ConnectionState.Closed) Then
setConnection()
End If
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter.SelectCommand = command
reader = command.ExecuteReader
'adapter.Fill(dt)
dt.Load(reader)
TableList.DataSource = dt
TableList.DisplayMember = "Tables_in_sampledata" 'What is displayed
TableList.ValueMember = "Tables_in_sampledata" 'The ID of the row
Catch ex As MySqlException
MessageBox.Show("Error1: " & ex.Message)
Finally
reader.Close()
conn.Close()
End Try
End Sub

Instead of SHOW TABLES, use the following query
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='YourDatabase';

Related

Transfer the sum of query to label

the query is working on mysql command line but how can i put the sum to the label
Dim SDA As New MySqlDataAdapter
Dim bSource As New BindingSource
Dim dbDataSet As New DataTable
Try
MysqlConn.Open()
Dim Query As String
Query = "select sum(No_Of_Case_To_Be_Deliver) from ordered= '" & totalcase.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
Never concatenate strings to build an Sql statement. Use parameters. You are risking damage to your database.
A DataAdapter will open and close its connection for you as part of the .Fill method. However, if it finds the connection open it leaves it open.
Glad to see you called .Dispose on your connection but you can save yourself the trouble by using `Using...End Using blocks. This will ensure that your database objects are closed and disposed even if there is an error.
Now to the code. You are not Filling or Updating anything so you don't need a DataAdapter for this query. You are not Binding anything so no BindingSource. Bad name for DataTable (dbDataSet) because a DataSet is a different type of object. Anyone trying to maintain your code could be easily confused.
By using parameters you not only save yourself from SQL injection but greatly simplify the Sql statement. No worries about double quotes, single quotes, etc.
Since you are retrieving only a single piece of data, you can use .ExecuteScalar which returns the first column of the first row of the result set.
I separated the code into a Data Access function and User Interface part. This way you can migrate your application to a different platform, say a web app, by just picking up the function as a whole.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lblTotalCases.Text = DirectCast(GetTotalCases(CInt(totalcase.Text)), String)
End Sub
Private Function GetTotalCases(OrderID As Integer) As Integer
Dim TotalCases As Integer
'I made up a query since your query didn't make sense.
Dim Query = "select sum(No_Of_Case_To_Be_Deliver) from OrderDetails Where OrderID = #ID;"
Using MysqlConn As New MySqlConnection("Your Connection String")
Using Command As New MySqlCommand(Query, MysqlConn)
Command.Parameters.Add("#ID", MySqlDbType.Int32).Value = OrderID
MysqlConn.Open()
TotalCases = CInt(Command.ExecuteScalar)
End Using
End Using
Return TotalCases
End Function

How do I check if the username value is already in the database in visual basic?

Private Sub SignUpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignUpBtn.Click
'ttp://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html
Try
cm = New OleDb.OleDbCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "INSERT INTO Users (UserName,UserPassword) VALUES (#Uname,#Pword)"
.Parameters.Add(New System.Data.OleDb.OleDbParameter("#UserName", System.Data.OleDb.OleDbType.VarChar, 255, Me.Uname.Text))
.Parameters.Add(New System.Data.OleDb.OleDbParameter("#UserPassword", System.Data.OleDb.OleDbType.VarChar, 255, Me.Pword.Text))
Me.Uname.Text = MainClass.consoleout
' RUN THE COMMAND
cm.Parameters("#UserName").Value = Me.Uname.Text
cm.Parameters("#UserPassword").Value = Me.Pword.Text
cm.ExecuteNonQuery()
MsgBox("Record saved.", MsgBoxStyle.Information)
Dim Form1 As New Form1
Form1.Show()
Hide()
Exit Sub
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
I'm trying to make this form with a check that if the username entered is the same as a username in the database. Currently I can save any user over and over again and the record is just repeated in the database. My username text box is called Uname and my password text box is called Pword. The database table is called Users and the columns I trying to put them is called UserName And UserPassword. My database connection has already been declared in the Module. I got all of the coding for this from a website(http://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html). I just modified it to suit my conditions. If someone could tell me how to make sure that no 2 usernames are saved in the database I would be very grateful.
Add a (or rather: the missing) unique index on the field Uname.
Then catch and handle the error when attempting to insert a duplicate.
make UNAME as primary key
and in code put try catch

vb.net Writing & Reading Multiline Text in MySQL Database

I'm trying to create a messaging system e.g. I have a table in a MySQL database called tbluser which holds the data for every user. One record is one user which has the field of 'StatusMessage'. This field can have values which can be written onto multiple lines, but I am having trouble on how to separate the text this field holds into multiple lines using a ListBox.
Private Sub lstMessages_VisibleChanged(sender As Object, e As EventArgs) Handles lstMessages.VisibleChanged
Dim Query As String = "SELECT StatusMessage FROM tbluser WHERE UserID=#userID"
Using Conn As New MySqlConnection(MySQL.ConnectionDetails)
Using Comm As New MySqlCommand()
With Comm
.Connection = Conn
.CommandText = Query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#userID", CInt(cboSelectUser.SelectedItem.ToString))
End With
Try
Conn.Open()
Dim Reader As MySqlDataReader = Comm.ExecuteReader
lstMessages.Items.Clear()
While Reader.Read OrElse (Reader.NextResult And Reader.Read)
lstMessages.Items.Add(Reader.GetString(0))
End While
Catch ex As MySqlException
End Try
End Using
End Using
End Sub
At the moment, all the text appears onto one line.
Also, another question, how would I insert text into the database with multiple lines.
To solve the problem, what I ended up doing was changing the component used into a RichTextBox. Also, I changed every instance of the string "\n" which is a new line in MySQL to Environment.NewLine().
To insert new messages into the field, I had to select all of the text already in the field and then add to that text so I used a combination of a SELECT query and UPDATE query along with Environment.NewLine() so I can write to new lines.

Populate a combobox with tables of a database in VB

I want to populate my combobox with the name of the tables of my database "converter" that has 3 tables. I'm using the following code:
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter = New MySqlDataAdapter(command.CommandText, conn)
adapter.SelectCommand = command
adapter.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "column_name"
ComboBox1.ValueMember = "column_name"
Catch ex As Exception
End Try
This code populates 3 items inside the combobox (which is the same as the number of tables inside my database). But what shows is this:
How can I populate my combobox with the exact name of my tables and not like this? I tried putting .toString on my dt but it's no good.
Can anyone help me? Thank you in advance. :)
EDIT
I used Steve's method and I was able to get the values. I used this code.
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter = New MySqlDataAdapter(command.CommandText, conn)
adapter.SelectCommand = command
dt = conn.GetSchema("TABLES")
adapter.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "table_name"
ComboBox1.ValueMember = "table_name"
Catch ex As Exception
End Try
But now it shows 3 additional empty values. refer to this image:
If I am right the correct values to pass to your combobox DisplayMember and ValueMember is
Tables_in_converter
In other words, the name of the only column returned by your command is built automatically using the fixed text "Tables_in_" followed by the <databasename>
If you want to use a different approach you could call the GetSchema method of the connection object in this way
using cnn = new MySqlConnection(...)
cnn.Open()
Dim dt = cnn.GetSchema("TABLES")
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "table_name"
ComboBox1.ValueMember = "table_name"
End Using

Get first entry from MySQL database in VB

Could you please help me? I just want to take the first row of a table in a mysql database via Visual Basic. I prefer simple code. The only thing i found is using a while, thing that i dont want. Thanks in advance!
Try something like this
Try
Dim sql As String = "SELECT first_row FROM test_table WHERE id = 1"
Dim cmd as OleDbCommand
cmd = New OleDbCommand(sql, Reconnect)
Dim itmReader as SqlDataReader
itmReader = cmd.ExecuteReader
If itmReader.Read Then
Dim firstRowData as String
firstRowData = itmReader.Item("first_row")
MessageBox.Show(firstRowData)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try