Reader if and else statement - mysql

I am practicing programming in visual basic
I have 2 forms in visual basic.
The first form has a command button that will show the input data from the 2nd form
The second form has a textbox where I need to input a data and save it.
The data that I input in the 2nd form stores it in MySQL
the 1st form has a command button named "Show my Grade" and if I click that I want to display the Form 2 and show me the grade. It does work however if I didn't input any grade and then I click the "show my grade" button it crashes I don't know the error. I tried using the code "if READER.HasRows Then:
but still it won't work
also tried if READER.Read then:
else MessageBox.Show("there is no grade input at the moment")
Please help.
This is my current code in the command button in form 1.
Me.Visible = False
Form2.Show()
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=qwerty;database=ssg"
Dim COMMAND As New MySqlCommand
Dim READER As MySqlDataReader
MySqlConn.Open()
COMMAND.Connection = MySqlConn
COMMAND.CommandText = "select grade from gradetable"
READER = COMMAND.ExecuteReader
Form2.TextBox1.Text = READER("grade")
End Sub
It works as long as I input a grade first, however if I didn't input any grade it crashes.
If I click the "Show my grade" button in form 1 without inputting a grade in form 2 I would like to just display a message saying "You still have no grade at the moment"
Please help.

The Using statement with a matching End Using. This is in place of Dim. It ensures that your objects are properly closed and disposed of even if there is an error. This is especially important for connections which should be closed as soon as possible.
I used the constructor of the connection to pass in the connection string. Setting the property is fine. This just saves a line of code.
Same idea with the command constructor. It can take the command text and the connection. Saves a little typing.
You had the right idea; using .HasRows. You just needed to add the READER.Read to get to the first record as explained in comments by jmcilhinney.
Private Sub GetGrade()
Using MySqlConn As New
MySqlConnection("server=localhost; userid=root; password=qwerty; database=ssg")
Using COMMAND As New MySqlCommand("select grade from gradetable", MySqlConn)
MySqlConn.Open()
Using READER As MySqlDataReader = COMMAND.ExecuteReader
If READER.HasRows Then
READER.Read()
Form2.TextBox1.Text = READER("grade")
Else
MessageBox.Show("Sorry, no grade yet.")
End If
End Using
End Using
End Using
End Sub

Related

how to loop through a data base for 21 button captions

ok i'm banging my head on my keyboard again. With help form here so far i did get my mysql query to read the one field i wanted. but my issue is this:
Concept. A table holds button data, like caption, and other stuff for latter on. Like what TAB the button will activate on a click. <-- the later is not important right now as once i figure out this part i'm asking about i can figure it out easily i'm sure. SO. i have 21 buttons. Each button needs a caption that is located in the database. What i'm trying to figure out is how to loop through the database to get the caption for botton 1, then button two, and so on. Right now it is loading the same caption for all 21 buttons. here is my code:
Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosdbDataSet.button_cat' table. You can move, or remove it, as needed.
Me.Button_catTableAdapter.Fill(Me.PosdbDataSet.button_cat)
'Procedures
Me.Show()
' Variables
Dim query As String
Dim command As MySqlCommand
Dim reader As MySqlDataReader
Dim TargetButton As Button
Try
'For button 1 through 21
dbconn()
For i As Integer = 1 To 21 Step 1
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
reader.Read()
'btn_Cat1.Text = reader("btn_caption")
'Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
reader.Close()
Next
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
I appreciate ANY HELP you can give me. i learn by seeing code and manipulating it to do what i need it to do.
I'm using visual studio 2015 community and MySQL for my database and writing in Visual Basic.
You are rerunning your query during every loop cycle.
Do something like this:
''For button 1 through 21
dbconn()
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
For i As Integer = 1 To 21 Step 1
reader.Read()
''btn_Cat1.Text = reader("btn_caption")
''Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
Next
reader.Close()
conn.Close()
Keep in mind that this code is potentially problematic in that it assumes that there will always be 21 results returned from the database.
If you want to prevent problems if there are fewer than 21 records returned, you can do something like this:
''For button 1 through 21
dbconn()
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
For i As Integer = 1 To 21 Step 1
If Not reader.Read() Then
''We are out of records. Exit the loop.
Exit For
End If
''btn_Cat1.Text = reader("btn_caption")
''Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
Next
reader.Close()
conn.Close()
You can also rewrite this as a while loop, but you would need to re-implement your i counter.

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.

Populating text boxes via Combobox and SQL database table

I am trying to populate a set of textboxes from a combobox on a form. The combo box is populated using a dataset when the form loads. When this is loaded it needs to show only one entry per unit number in the kitcombobox (which is a unit number for a kit with multiple pieces of equipment in it) but display the multiple pieces of equipment's information in the different text boxes when the unit number is selected via the kitcombobox. What approach should I take towards this? I'm really lost and this is all I have so far :(
Private Sub ckunit()
Dim ds As New DataSet
Dim cs As String = My.Settings.MacroQualityConnectionString
Dim kitcombobox As String = "SELECT DISTINCT Unit_Number, Status FROM Calibrated_Equipment WHERE CHARINDEX('CK', Unit_Number) > 0 AND Status='" & ckstatuscombbx.Text & "'"
Dim sqlconnect As New SqlConnection(cs)
Dim da As New SqlDataAdapter(kitcombobox, sqlconnect)
sqlconnect.Open()
da.Fill(ds, "Calibrated_Equipment")
sqlconnect.Close()
kitcombbx.DataSource = ds.Tables(0)
End Sub
Assuming you are using WinForms, I think the key will be adding an event handler for the SelectionChangedCommitted event on kitcombbx.
You can then checked the properties on the combobox to check what is selected and run another query to pull equipment information for that kit. It'd probably look something like this:
Private Sub kitcombbx_SelectionChangeCommitted(sender As Object, e As EventArgs) _
Handles kitcombbx.SelectionChangeCommitted
Dim kit = kitcombbx.SelectedItem.ToString()
Dim kitEquipment = FetchKitEquipmentInformation(kit)
PopulateEquipmentInformation(kitEquipment)
End Sub
The way you're currently constructing your query (by concatenating string parameters directly from user input) results in bad performance for most database systems, and moreover, is a huge security vulnerability. Look up SQL injection for more detail (or read these two questions).
Better DB code would probably look something like this:
Dim query = New StringBuilder()
query.AppendLine("SELECT DISTINCT Unit_Number, Status ")
query.AppendLine("FROM Calibrated_Equipment ")
query.AppendLine("WHERE CHARINDEX('CK', Unit_Number) > 0 ")
query.AppendLine(" AND Status = #STATUS ")
Dim connection As New SqlConnection(My.Settings.MacroQualityConnectionString)
Dim command As New SqlCommand(query, connection);
command.Parameters.Add("#STATUS", ckstatuscombbx.Text);
Dim da As New SqlDataAdapter(kitcombobox, sqlconnect)
'And so on...
Your question is a bit broad (and therefore, likely off-topic for StackOverflow), see How to Ask.

VB.net data retrieval and display

So, for some reason I can't work out I think the below is only retrieving the 1st letter of the value within the column I'm trying to search. (Note: the database is called m1 and contains 11 columns in total).
I tested the query first in SQL Admin and it worked properly (I think).
I then wrote this myself using documentation, I think I've more that likely made a mistake somewhere..
Dim hostnameQuery As String = "SELECT `HOSTNAME` FROM `m1` WHERE 1"
Dim SQLConnection As New MySqlConnection(My.Settings.connStr)
Dim cmd As New MySqlCommand(hostnameQuery, SQLConnection)
Try
SQLConnection.Open()
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
I added this to a button click so when I click the button only the letter 'M' appears but the value is 'M1'
What have I done wrong?
That's because you requested only a character. Try using GetString() instead of GetChar() :
main.Label64.Text = (reader.GetString(0))
There are many things that can be improved in your code.
First of all, you can remove the condition WHERE 1, because it means "EVERYTHING" so it is not useful.
Secondly, you can avoid calling cmd.ExecuteNonQuery() because it is usually used to run an instruction that does not return anything (like INSERT).
Finally, if you are interested only to the first returned row, you can avoid the While loop and use cmd.ExecuteScalar() instead.
To summarize, instead of:
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
simply do this:
main.Label64.Text = Convert.ToString(cmd.ExecuteScalar())

How to upload what user selected in combo box to MYSQL database

ok so in vb i have a combo box that i populated with selections for the user to choose from. i want what ever the user selects to upload to the db. I have other things in my form uploading to my db but i cant get what the user selected to upload?? how would i do this.
here is my code for the other upload stuff that i did.
Try
Dim cmd2 As New MySqlCommand
Dim insertStatment As String = "INSERT INTO comment (name,comment) VALUES
(#name,#comment)"
cmd2 = New MySqlCommand(insertStatment, db_con)
cmd2.Parameters.AddWithValue("#name", txtname.Text)
cmd2.Parameters.AddWithValue("#comment", richtxtcomment.Text)
cmd2.ExecuteNonQuery()
MessageBox.Show("Thank your for your comment")
Catch ex As Exception
MessageBox.Show("bad")
In general, for a ComboBox you'll need to do something like this:
cmd2.Parameters.AddWithValue("#whatever", combobox.SelectedValue);