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
Related
I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function
I am using MYSQL database for that...I get this following Error...Please anyone can help me?
Imports System.Data
Imports MySql.Data Imports MySql.Data.MySqlClient
Public Class formLogin
Dim connStr As String = "server=localhost;user=root;database=ssknet;port=3306;password=;"
Dim connection As New MySqlConnection(connStr)
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
connection.Open()
Dim cmd As New MySqlCommand("SELECT * FROM user WHERE username=#username and password=#password", connection)
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = txtPassword.Text
Dim adapter As New MySqlDataAdapter
Dim table As New DataTable
adapter.Fill(table)
If table.Rows.Count <= 0 Then
MessageBox.Show("Invalid Username or Password")
Else
MessageBox.Show("Login Success!")
End If
'cmd.ExecuteNonQuery()
connection.Close()
End Sub
End Class
I want to access database right now. Quick frnds
You are missing a critical step. You are not assigning any command to your adapter. It doesn't know how to query anything without a command
Dim adapter As New MySqlDataAdapter(cmd)
Next, according to the MySql Reserved KeyWords, user and password are reserved and to use them in a query as field names you should put backticks (ALT+096) around them. So the query should be written as
Dim cmd As New MySqlCommand("SELECT * FROM `user`
WHERE username=#username
AND `password`=#password", connection)
A part from this your code is good enough albeit there are a couple of thing to consider.
First, connection object should not be kept as global objects. This leads to many problems with the resources kept on the server and with closing/opening the connection when there is an error. Just create and discard the connection inside a using statement
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Using connection = New MySqlConnection(connStr)
connection.Open()
.... all of your code except the close connection
End Using ' this close the connection also in case of exceptions
Second, you don't need an SqlDataAdapter and a datatable if you just want to check if the user/password exists
Dim reader = cmd.ExecuteReader()
if reader.HasRows then
MessageBox.Show("Login Success!")
Else
MessageBox.Show("Invalid Username or Password")
End If
Third, it is a great security risk to keep password in plain text inside your database and then using queries to retrieve it. You should use Salt and Hashing methods to store and retrieve password
I have the following functional code:
Call ConnSettings()
Dim objDs As New DataSet
Dim Query As String
Query = "the query"
Cmd = New MySqlCommand(Query, MysqlConn)
Dim dAdapter As New MySqlDataAdapter
dAdapter.SelectCommand = Cmd
''Dim dAdapter As New MySqlDataAdapter(Query, MysqlConn)
Try
MysqlConn.Open()
dAdapter.Fill(objDs)
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
I have noticed that the code is equally functional if I also use
Dim dAdapter As New MySqlDataAdapter(Query, MysqlConn)
instead of:
Cmd = New MySqlCommand(Query, MysqlConn)
Dim dAdapter As New MySqlDataAdapter
dAdapter.SelectCommand = Cmd
Obviously, I would like to use a single line instead of three. However, I am fairly new to VB and would like to know if there are any issues with doing that.
Let's try to improve your code....
First ConnSettings doesn't initialize a global connection variable but a local one and returns it
Public Function ConnSettings() As MySqlConnection
Dim conn As MySqlConnection
conn = new MySqlConnection(yourConnectionStringHere)
conn.Open()
return conn
End Function
Now the code that needs a MySqlConnection could call this ConnSettings and put the return value in a Using Statement
objDS = new DataSet()
Try
Using conn = ConnSettings()
Using dAdapter = New MySqlDataAdapter(theQuery, conn)
dAdapter.Fill(objDs)
End Using
End Using
Catch(ex as Exception
MessageBox.Show(ex.Message)
End Try
This code puts the connection returned in a Using Statement. When the code flows out of the Using Statement the connection is closed and disposed (same for the MySqlDataAdapter) As you can see there is no need for the Finally clause and the Try/Catch block is present just because you want to give an error message to your user (while this is a common practice there is no really sense to put your user in the unconfortable position to try to understand these technically dense messages, better use a log file and advise your user to send the log to you)
In this context also the code inside the ConnSettings is a bit useless. What you really need is just the connectionstring and you could write the creation of the MySqlConnection directly in the calling code.
I have a MySQL database with the columns TIME and METHOD, which have about 15,000+ rows of data. I need to get these columns/rows to display on a DataGridView within a vb.net form. I am using the MySql.Data.dll to connect to the database and run my queries. Below is my current code:
Private Sub RetreiveData() Handles Button.click
Dim dt As New DataTable
Dim connectionString As String = "server=ipaddress;database=debugging;user id=root;password=password;port=3307"
Dim connection As MySqlConnection = New MySqlConnection(connectionString)
Try
connection.Open()
Dim sql As String = String.Format("SELECT time, method FROM test1 WHERE custPin='{0}' AND dataID='{1}' ORDER BY TIME;", customerPin, sessionID)
Dim dAdapter As MySqlDataAdapter = New MySqlDataAdapter(Sql, connection)
dAdapter.Fill(dt)
Catch ex As Exception
MessageBox.Show("ERROR: " & ex.Message & Environment.NewLine & ex.StackTrace & Environment.NewLine)
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try
Me.dgvCustomerData.DataSource = dt
connection.Close()
End Sub
Note: "dgvCustomerData" is my DataGridView on my form, and "customerPin"/"sessionID" are retrieved from TextBoxes on my form as well.
I have checked through about 20-30 forum posts that state I should bind my data, or use different styles of data adapters, but none have been able to display my data. I can get it to create the two columns, however, no data is filled in. Any assistance would be very helpful, thanks in advanced.
I have a windows form app with a DataGridView populated by a TableAdapter. I'm using the Fill method to update the data for the UI in a looping Async sub like so.
Private Async Sub updateUI()
Dim sw As New Stopwatch
While True
Await Task.Delay(3000)
sw.Restart()
'myTableAdapter.Fill(getDataWithMySQL())
'myTableAdapter.Fill(myDataSet.myTable)
myTableAdapter.Fill(myDataSet.myStoredProc)
logger.Debug(sw.ElapsedMilliseconds)
End While
End Sub
The getDataWithMySQL function is as follows:
Private Function getDataWithMySQL() As myDataSet.myDataTable
Dim connStr As String = My.Settings.myConnectionString
Dim sql As String = "SELECT ... LEFT JOIN ..."
Dim dt As New myDataSet.myDataTable
Using conn As New MySqlConnection(connStr)
Using cmd As New MySqlCommand()
With cmd
.CommandText = sql
.Connection = conn
End With
Try
conn.Open()
Dim sqladapter As New MySqlDataAdapter(cmd)
sqladapter.Fill(dt)
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Using
End Using
Return dt
End Function
myDataSet.myTable is the same as myDataSet.myStoredProc except it is created by joining tables in the DataSet designer. Obviously myDataSet.myStoredProc is the same query in a stored procedure in the source database.
So benchmarking the Fill with each method using a Stopwatch I get the following results:
myDataSet.myStoredProc
~750ms
myDataSet.myTable
~550ms
getDataWithMySQL()
<10ms
So my question is, what is causing the performance difference here? I'd prefer to use myDataSet.myTable or myDataSet.myStoredProc but I don't know if it is possible to optimise them in some way so as to match the performance of getDataWithMySQL().