I am making a Student Profile System and I have a form on VB that retrieves data from MySQL to Checkboxes, when there is "1" on the column, the checkbox ticks.
I do this function and queries that was stated below on every single checkboxes. Is there any way to merge this into one query?
Sub CheckboxAccess1()
Using con As New MySqlConnection(str)
Try
con.Open()
Dim sql As String = "SELECT access1 FROM tblusers WHERE userid = #userid AND access1 LIKE '1'"
com = New MySqlCommand(sql, con)
com.Parameters.AddWithValue("userID", TextBox2.Text)
Dim reader As MySqlDataReader
reader = com.ExecuteReader
If reader.Read() Then
CheckBox2.Checked = True
Else
CheckBox2.Checked = False
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
con.Dispose()
End Try
End Using
End Sub
Sub CheckboxAccess2()
Using con As New MySqlConnection(str)
Try
con.Open()
Dim sql As String = "SELECT access2 FROM tblusers WHERE userid = #userid AND access2 LIKE '1'"
com = New MySqlCommand(sql, con)
com.Parameters.AddWithValue("userID", TextBox2.Text)
Dim reader As MySqlDataReader
reader = com.ExecuteReader
If reader.Read() Then
CheckBox3.Checked = True
Else
CheckBox3.Checked = False
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
con.Dispose()
End Try
End Using
End Sub
Sub CheckboxAccess()
Using con As New MySqlConnection(str)
Try
con.Open()
Dim sql As String = "SELECT access1, access2 FROM tblusers WHERE userid = #userid"
com = New MySqlCommand(sql, con)
com.Parameters.AddWithValue("userID", TextBox2.Text)
Dim reader As MySqlDataReader
reader = com.ExecuteReader
reader.Read()
CheckBox2.Checked = (reader.GetString("access1") = "1")
CheckBox3.Checked = (reader.GetString("access2") = "1")
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
con.Dispose()
End Try
End Using
End Sub
Related
I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using
Using conn As New MySqlConnection("server=localhost;user=root;password=;database=dbrentalsystem")
conn.Open()
Dim commandReader As New MySqlCommand("select * from tbl_unit", conn)
Dim reader As MySqlDataReader = commandReader.ExecuteReader
While reader.Read
If reader.IsDBNull(2) Then
lblUnit1.Text = "Vacant"
Else
lblUnit1.Text = "Occupied"
End If
End While
commandReader.Dispose()
reader.Close()
con.Close()
End Using
Here's my code, I just want to check if there is data in column 2, row 3
A fast and somewhat dirty approach is add a count and count to 3 in the reader.. This is bar far not the best solution to the task, but it will work :)
Using conn As New MySqlConnection("server=localhost;user=root;password=;database=dbrentalsystem")
conn.Open()
Dim commandReader As New MySqlCommand("select * from tbl_unit", conn)
Dim reader As MySqlDataReader = commandReader.ExecuteReader
Dim i as integer = 1
While reader.Read
if i = 3 then
If reader.IsDBNull(2) Then
lblUnit1.Text = "Vacant"
Else
lblUnit1.Text = "Occupied"
End If
end if
i += 1
End While
commandReader.Dispose()
reader.Close()
con.Close()
End Using
There are 10 rows in primary_student_table.
When I execute the following code, the result was -1.
Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "
cmd = New SqlCommand(query, con)
count = cmd.ExecuteNonQuery
MsgBox(count)
con.Close()
What's the problem in the above code?
You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
SqlCommand.ExecuteScalar Method
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exceptions
Example Code:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using
The solution is to replace
count = cmd.ExecuteNonQuery
with
count = cmd.ExecuteScalar
Like Robert Beaubien said in his comments
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "Select * from dblms.accounts"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the value in count will be the number of rows in a table :) hope this helped
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
dbQuery = "select * from main_table"
myCommand.CommandText = dbQuery
myCommand.Connection = conn
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
While myReader.Read()
row_count = row_count + 1
End While
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
MessageBox.Show(row_count)
conn.Close()
When I run the above code, it displays the correct row count. However, I am trying to get the data into an arraylist one row at a time. Using the code below does not give me an error but it only reads in the first row and then stops executing.
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
dbQuery = "select * from main_table"
myCommand.CommandText = dbQuery
myCommand.Connection = conn
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
While myReader.Read()
For x As Integer = 0 To myReader.FieldCount
col_array.Add(myReader.GetString(x))
Next
End While
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
conn.Close()
I don't understand why it is stopping after the first row is read in.
As commented:
Iterating from 0 to FieldCount will throw an IndexOutOfRangeException which will break after the first row.
For x As Integer = 0 To myReader.FieldCount
col_array.Add(myReader.GetString(x))
Next
Change it to end at myReader.FieldCount - 1 to fix this.
I have queried my MySql database and data is stored in a dataset named Search Events(I have checked this and it works)
However when i try to pass this data into a datagridview and then ultimately my array it doesn't seem to work :( The problem seems to be that no data is being passed from Search Events into Table
Any ideas??
Dim Table As New DataGridView
Table.DataSource = SearchEvents.Tables("Event ID")
Dim EventID(Table.Rows.Count - 1) As String
For i = 0 To 12
EventID(i) = Table.Rows(0).Cells(i).Value
Next
'Try the following function
Public Sub getuserlist()
Dim con As New MySqlConnection(ConnectionString)
Try
If con.State <> ConnectionState.Open Then
con.Open()
End If
Dim selecttaxinv = "SELECT * FROM user_tb WHERE user_status = 'Active' ORDER BY date_registered DESC"
Dim myCommand As New MySqlCommand(selecttaxinv, con)
Dim dr As MySqlDataReader
dr = myCommand.ExecuteReader()
yourdatagridview.Rows.Clear()
Dim b = 1
While dr.Read()
Dim fullname As String = dr("fname") & " " & dr("mname") & " " & dr("lname")
Dim row As String() = New String() {dr("user_id"), b, fullname, dr("fname"), dr("date_registered")}
yourdatagridview.Rows.Add(row) 'print list
b += 1
End While
dr.Close()
If con.State = ConnectionState.Open Then
con.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub