How to display data between two dates in mysql vb - mysql

I have a form that is responsible for displaying sales that were made based on date. I have got two date pickers FROM & TO. What I want is when I want to search data example from 12 to 19th it only displays 13th and 19th, I want it to show dates between 12 and 19 i.e. 12th,13th,14th,15th,....till 19th, But it only shows two dates 13th and 19th which I haven't asked in the date picker. I selected 12 and 19 and it displayed 13 and 19. In my database, I can 12th date is there on the database. I tried to check my code where I went wrong and followed the same MySQL syntax for selecting data from the database based on data.
This is my code:
Private Sub btnShowAll_Click(sender As Object, e As EventArgs) Handles btnShowAll.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=golden_star"
''connecting data grid with the database
Dim Sda As New MySqlDataAdapter
Dim dbdataset As New DataTable
Dim bSource As New BindingSource
Try
MysqlConn.Open()
Dim Query As String
Dim sum As Decimal = 0
Query = "select * from sales where date between '" + FromDate.Text + "' and '" + ToDate.Text + "'"
Command = New MySqlCommand(Query, MysqlConn)
Sda.SelectCommand = Command
Sda.Fill(dbdataset)
bSource.DataSource = dbdataset
DataGridView1.DataSource = bSource
Sda.Update(dbdataset)
For i = 0 To DataGridView1.Rows.Count - 1
sum += DataGridView1.Rows(i).Cells(8).Value
Next
lblSum.Text = sum
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
THIS IS THE OUTPUT OF THE CODE:
https://snipboard.io/PdpcUz.jpg
I have already declared the MySQL command and the imports in my code above.
I don't know where I went wrong or have I missed a piece of code somewhere?
Please help. Thank you.

This is how I would write that code:
Query = "select * from sales where date >= #init AND date <= #end"
Command = New MySqlCommand(Query, MysqlConn)
Command.Parameters.Add("#init", MySqlDbType.Date).Value = From.Value.Date
Command.Parameters.Add("#end", MySqlDbType.Date).Value = To.Value.Date
Sda.SelectCommand = Command
Sda.Fill(dbdataset)
bSource.DataSource = dbdataset
DataGridView1.DataSource = bSource
Now the query text has no more concatenations but just parameters placeholders and the search is executed using the standard operators.
The command itself is loaded with two parameters matching the placeholders'name. Important part is the parameter type that should match the database column type and finally I take the Value property that is a DateTime and not a string representation of it and use only the Date part of that value

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

vb 2010 mysql insert record operation inserts a blank record but no data is inserted

I am trying to develop a utility in vb 2010, which will store values from Datagridview control to a mysql table
Steps
1) Datagrid cell values are stored in an array
2) Array values are used .AddWithValue() function
Present status: Only a blank record is inserted. Data is missing.
Please refer to following code.
Function insertRec()
'dgExistingProject is datagridview control embedded on the form
Dim ServerString As String = "Server=pnserver;User ID=root;
Password=; Database=prayer_net"
Dim Arr(RCount) As String
Dim SQLConn As MySqlConnection = New MySqlConnection
SQLConn.ConnectionString = ServerString
dim I as Integer
For I = 0 To RCount
Arr(I) = dgExistingProject.Rows(I).Cells(1).Value
Next
Try
Dim dt As Date = DateTime.Now.ToString("yyyy/MM/dd
HH:mm:ss")
Dim projName as Integer=Arr(4)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "INSERT INTO dyn_dwg_register
(file_name,file_location,dwg_description,
project_id,created_by, created_on)" & _
" values (#file_name, #file_location, #dwg_description, #project_id, #created_by, #created_on)"
.CommandType = CommandType.Text
.Connection = SQLConn
.Parameters.AddWithValue("#file_name", Arr(0))
.Parameters.AddWithValue("#file_location", Arr(1))
.Parameters.AddWithValue("#dwg_description", Arr(2))
.Parameters.AddWithValue("#project_id", ProjName)
.Parameters.AddWithValue("#created_by", Arr(4))
.Parameters.AddWithValue("#created_on", dt)
End With
Try
SQLConn.Open()
If SQLConn.State = ConnectionState.Open Then
Dim ID As Integer = sqlCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConn.Close()
End Try
End Using
Catch e As Exception
MsgBox (e.Message.ToString)
End Try
End Function
Rajendra Nadkar
i had written a code in C# where i had to store data from a datagrid to SQL database. I used the following code. I think it will help you.
string sqlquery = "UPDATE TableName set ColumnName1=#param1 where ColumnName2=#param2";
using (OleDbCommand Cmd = new OleDbCommand(sqlQuery, dbCon))
{
Cmd.Parameters.AddWithValue("#param1", Convert.ToDouble(dataGridView1[1, index].Value));
Cmd.Parameters.Add(new OleDbParameter("#param2", OleDbType.VarWChar)).Value = "somevalue";
updateDbCmd.ExecuteNonQuery();
updateDbCmd.Parameters.Clear();
}
Funny, I changed the field name prefix # to ? and things became smooth. In an earlier question in Feb 11, Stelian Matei suggested this edit, though later on Giezel Esteves reversed it. (Original question asked by user1176607 in Feb '10)
I guess I need to refer to documentation more thoroughly. Anyways I am giving the working code here if you or anybody interested in it.
Dim qry As String = "INSERT INTO dyn_dwg_register (`file_name` , `file_location`, `dwg_description`, `project_id`, `created_by`)" & _
" values (?file_name, ?file_location, ?dwg_description, ?project_id, ?created_by)"
Dim sqlCommand As MySqlCommand
sqlCommand = New MySqlCommand(qry, SQLConn)
sqlCommand.CommandType = CommandType.Text
With sqlCommand
.Parameters.AddWithValue("?file_name", Arr(0))
.Parameters.AddWithValue("?file_location", Arr(1))
.Parameters.AddWithValue("?dwg_description", Arr(2))
.Parameters.AddWithValue("?project_id", ProjName)
.Parameters.AddWithValue("?created_by", Arr(2))
End With

Clear Databound datagridview vb.net

I have a datagridview that gets data from the database, it's working fine but then when i close the form and open it again it wont clear the previous content. It will output the previous selection with the new selection made.
I have tried this codes:
compSpecs.modelDatagridview1.DataSource = Nothing
compSpecs.modelDatagridview1.Rows.Clear()
compSpecs.modelDatagridview1.Columns.Clear()
But it still wont clear. Maybe i'm not doing it right. Please help.
This is my code:
Private Sub load_model2()
conn = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=p#ssw0rd; database= atos_db"
Dim sda As New MySqlDataAdapter
Dim bsource As New BindingSource
compSpecs.modelDatagridview2.DataSource = Nothing
compSpecs.modelDatagridview2.Rows.Clear()
compSpecs.modelDatagridview2.Columns.Clear()
Try
conn.Open()
Dim query As String
query = "select * from atos_db.itemdetails_tbl left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where item='" & itemCombobox2.Text & "'"
comm = New MySqlCommand(query, conn)
sda.SelectCommand = comm
sda.Fill(dbDataset)
bsource.DataSource = dbDataset
compSpecs.modelDatagridview2.DataSource = bsource
sda.Update(dbDataset)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Firstly, that implies that you're using the same instance of the form each time. If you create a new instance of the form each time you want to display it then there can't be anything left over from last time.
If you don't want to do that though, there's no use unbinding the grid from the data source if you're only going to rebind it again. If the data is still in the data source then the grid will just display it again. If you want to get rid of the data then you need to clear the data source. The grid displays what's in the data source so clear the data source and the grid will be cleared too.

Update multiple rows in mysql?

I need to know to to update more than one rows in database using vb.net.
In my database it have 3 rows (have id for each other ) and on my vb.net I have 3 text boxes. I need to update data using those 3 text boxes in one shot.
here is my vb.net code
MysqlConn.Open()
Dim Query As String
Query = "update cs set subject=#subject, place=#place where=#id"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Data Saved")
MysqlConn.Close()
You need to pass parameters
Dim sql as String = "update cs set subject=#subject, place=#place where id=#id" ' NOTE: id = #id
cmd = New MySqlCommand(sql, MysqlConn)
cmd.Parameters.addWithValue("#subject", txtSubject.Text)
cmd.Parameters.addWithValue("#place", txtPlace.Text)
cmd.Parameters.addWithValue("#id", CInt(txtId.Text)) ' id is int , I hope
' instead of reader do ExecuteNonQuery
Dim ret = cmd.ExecuteNonQuery()
MessageBox.Show("Success: " & (ret > 0).ToString())
You can also do ExecuteReader but you do that when you return something. I don't know MySql but in Sql Server you can use Output with Insert and Update. And you can use ExecuteReader to get this output.

Need help filling datagrid from MySQL

I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).