Hi im having a little problem with vb.net not sure which direction to head really.
The front end of the program is used to count seconds of a certain downtime of a process.
Database has the following table, and an example data:
status | startdate | stopdate | Seconds
Running 27/08/2012 11:10:11 27/08/2012 11:10:22 11
Running 27/08/2012 11:10:11 27/08/2012 11:10:22 11
Running 27/08/2012 12:14:27 27/08/2012 12:14:57 30
On the back end all im trying to do is populate a label with the sum of seconds using a datepicker for the date, and when doing the query i use the datepicker text and add the time on to the end of it, to no suprise it didnt work, also it only takes the start date into account, but not the stopdate as im trying to add up within that time frame, and im hopeing someone could help, this is the code i tried below:
Dim DTimePicker1 = DateTimePicker1.text & " 11:00:00"
Dim DTimePicker2 = DateTimePicker1.text & " 12:00:00"
cmd.Parameters.Clear()
cmd.CommandText = "SELECT SUM(seconds) FROM sqlccmlinestatus WHERE status = 'Running' and startdate BETWEEN #BEG AND #END"
cmd.Parameters.AddWithValue("#BEG", DTimePicker1)
cmd.Parameters.AddWithValue("#END", DTimePicker1)
Label70.Text = cmd.ExecuteScalar()
Any help would be great.
Many Thanks,
Pete
Dim D1 as Date = DateTimePicker1.Value
Dim D2 as Date = DateTimePicker2.Value
Dim DTimePicker1 as new Date(D1.Year, D1.Month, D1.Day, 11, 0, 0)
Dim DTimePicker2 as new Date(D2.Year, D2.Month, D2.Day, 12, 0, 0)
cmd.Parameters.Clear()
cmd.CommandText = "SELECT SUM(seconds) FROM sqlccmlinestatus WHERE status = 'Running' and startdate BETWEEN #BEG AND #END"
cmd.Parameters.AddWithValue("#BEG", DTimePicker1.ToString("yyyy-MM-dd HH:mm:ss.fff"))
cmd.Parameters.AddWithValue("#END", DTimePicker2.ToString("yyyy-MM-dd HH:mm:ss.fff"))
Label70.Text = cmd.ExecuteScalar()
Related
Im saving some calculated values in to database each month.Before saving, i want to check data is already available for this month and year. IF the same month exists, then user has to select another month or leaving without saving that. In Vb.net, im using DateTimepicker for selecting month and save that in DateTIme format in mysql. In that i want to check only month and year is existing.
Mysql:
1 2019-05-01 14:24:20 ProA 8.34 3.59
2 2019-05-01 14:24:20 ProB 9.21 5.54
Here record available for ProA for May2019 is available. So user cannot save for may 2019 again.
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
conn.Open()
sQuery = "SELECT * FROM riskanalysis WHERE DATE_FORMAT(reportdate,'%c %Y') >= #StartDate "
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("#StartDate", startDate)
Using reader As MySqlDataReader = cmd_listview.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("Record Already Exist for this Month!", MsgBoxStyle.Exclamation, "Select another month!")
Else
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("dat", DateTimePicker1.Value)
cmd_listview.Parameters.AddWithValue("process", ProcessRiskGridView.Rows(i).Cells(0).Value)
cmd_listview.Parameters.AddWithValue("avgrisk", ProcessRiskGridView.Rows(i).Cells(1).Value)
cmd_listview.Parameters.AddWithValue("riskafterimp", ProcessRiskGridView.Rows(i).Cells(2).Value)
cmd_listview.ExecuteNonQuery()
Next
End Using
conn.Close()
I tried for some mysql command but it didnt work.
You don't need to Select * to find out if a record exists. Just get the count. Don't retrieve data you don't need. You certainly don't need a reader.
Keep your database objects local so you can be sure they are closed and disposed. `Using...End Using blocks will handle this for you even if there is an error.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
You keep adding parameters to the collection over and over on each iteration. They only need to be added once. The value of #dat remains the same for all iterations. Only the values of the last 3 parameters change. You seem to be mixing up column names and parameter names. We are dealing with parameter names.
I have guessed at datatypes. Check your database for the actual datatypes and be sure to convert the values from the grid cells to the proper type if necessary. I don't know what kind of grid you are using and if it returns proper datatypes for .Value.
Example:
cmd.Parameters("#avgrisk") = CDbl(ProcessRiskGridView.Rows(i).Cells(1).Value)
Private Sub MySql()
Dim retVal As Integer
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
Dim sQuery = "SELECT Count(*) FROM riskanalysis WHERE DateTimeColumnName >= #StartDate; "
Using conn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, conn)
cmd.Parameters.Add("#StartDate", MySqlDbType.DateTime).Value = startDate
conn.Open()
retVal = CInt(cmd.ExecuteScalar)
End Using
End Using
If retVal <> 0 Then
MessageBox.Show("Record Already Exist for this Month!")
Return
End If
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, cn)
With cmd.Parameters
.Add("#dat", MySqlDbType.DateTime).Value = selectedDate
.Add("#process", MySqlDbType.VarChar)
.Add("#avgrisk", MySqlDbType.Double)
.Add("#riskafterimp", MySqlDbType.Double)
End With
cn.Open()
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd.Parameters("#process").Value = ProcessRiskGridView.Rows(i).Cells(0).Value
cmd.Parameters("#avgrisk") = ProcessRiskGridView.Rows(i).Cells(1).Value
cmd.Parameters("#riskafterimp") = ProcessRiskGridView.Rows(i).Cells(2).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
Using SQL Server Management Tools I created a view with the following
SELECT ID,
Groupname,
CONVERT(VARCHAR, TimeSub, 103) AS Date,
RIGHT(CONVERT(CHAR(20), TimeSub, 22), 11) AS Time,
TK,
CProblem,
Fix,
Username,
Closed_Date,
Reason
FROM dbo.log
I needed to seperate TimeSub into 2 fields 1 for Date and 1 for Time in AM/PM.
Using VB2012
Dim sqlSelectCommand As New SqlCommand(("Select * from log order by ID DESC"), CS)
Dim adapter As New SqlDataAdapter(sqlSelectCommand)
adapter.Fill(DTable)
BS.DataSource = DTable
DG1.DataSource = BS
BS.Filter = ("Date >= '" & Date.Now.ToString("dd/MM/yyyy") & "'")
'BS.Filter = ("Groupname = 'SW'")
What should happen is the datadridview should only show todays date based on the Date Column, it doesn't work, it shows all dates.
If I used the Groupname SW it sorts Groupname showing all records with SW in them. To me it's like the convert in the SQL view isn't working properly.
Any help appreciated.
my first time doing a date calculation on my system
as you can see here on my first query how would i say that my expdate table is equal to this current date? then if so msgbox me "your item has expired"
on my second query i wanted to set a msgbox where msgbox me three months before my expdate ?
heres what i tried to do
cn.Open()
Dim query As String
query = "Select * from tblmeds where TIMESTAMPDIFF(MONTH,`expdate`,CURRENT_TIMESTAMP())< 1"
command = New MySqlCommand(query, cn)
readers = command.ExecuteReader
Dim count As Integer
count = 0
While readers.Read
count = count + 1
End While
cn.Close()
If count = 1 Then
msgbox "you have a expired items"
else
"no items are at risk"
PS:i am currently using PHPMYADMIN as my database
Assuming SQL SErver...
Subtract 3 months from the expiration date and compare that to the utc date (if multiple timezones are involved) otherwise you could just use getDate()
SELECT EXPDATE
FROM tblMeds
WHERE Dateadd(Month, -3,expDate) < = getutcdate()
If you change you query to
query = "Select count(*) as cnt from tblmeds where TIMESTAMPDIFF(MONTH,`expdate`,CURRENT_TIMESTAMP())< 1"
Then you won't need a look to count the rows, the server can do that which is faster.
Hello Everyone Good Afternoon,
I have 5 Fields in MySQL and there are:
ItemCode
Description
OrderQty
ApprovedQty
UoM
UnitPrice
Total
I cant explain it using proper words but I hope you will understand it by letting me show to you the table.
_______________________________________________________________
|ItemCode|Description|OrderQty|ApprovedQty|UOM|UnitPrice|Total|
---------------------------------------------------------------
|12345678|Ketchup |12.00 |0.00 |PC |1.00 |12.00|
|67891111|Soy Sauce |0.00 |12.00 |PC |1.00 |12.00|
---------------------------------------------------------------
Now you see it, I hope you can understand it now.
Here is my Question, I have a Code that will transfer the Data above into a Datagridview but theres a twist and that twist is the Question.
Here it is:
How can I Display the Data like this; If ApprovedQty is 0.00 then the Data in the OrderQty will display but if ApprovedQty is not 0.00 regardless of what data is in the OrderQty the ApprovedQty will be Show.
Something like this.
Based on the Table above
___________________________________________________
|ItemCode|Description|OrderQty|UOM|UnitPrice|Total|
---------------------------------------------------
|12345678|Ketchup |12.00 |PC |1.00 |12.00|
|67891111|Soy Sauce |12.00 |PC |1.00 |12.00|
---------------------------------------------------
Here is my code but it only shows the Approved Qty
Private Sub loadfinalpurch1()
Dim con1 As MySqlConnection = New MySqlConnection("server=localhost;userid=root;password=admin1950;database=inventory")
Dim sql1 As MySqlCommand = New MySqlCommand("Select ItemCode,Description,ApprovedQty,UoM,UnitPrice,Total from final_purch where PRnumber = '" & Label2.Text & "' and Added is NULL OR Added ='';", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Item Code"
.Columns(1).HeaderCell.Value = "Description"
.Columns(2).HeaderCell.Value = "Order Qty"
.Columns(3).HeaderCell.Value = "UOM"
.Columns(4).HeaderCell.Value = "Unit Price"
.Columns(5).HeaderCell.Value = "Total Amount"
End With
DataGridView1.Columns.Item(0).Width = 90
DataGridView1.Columns.Item(1).Width = 200
DataGridView1.Columns.Item(2).Width = 90
DataGridView1.Columns.Item(3).Width = 90
DataGridView1.Columns.Item(4).Width = 100
DataGridView1.Columns.Item(5).Width = 100
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
I hope you get my point.Do I have something to do with the MYSQL Command? with My Code? I don`t know how to achieve this.
TYSM For Future Help
You don't do that condition anywhere, you could do it on your code or directly changing your query:
Select ItemCode,
Description,
IF(ApprovedQty = 0, OrderQty, ApprovedQty) as myApprovedQty,
UoM,
UnitPrice,
Total from final_purch where PRnumber = '" & Label2.Text & "' and Added is NULL OR Added ='';", con1
You should implement this in your SQL using a case statement.
https://dev.mysql.com/doc/refman/5.7/en/case.html
The above answers using the IF() function are correct, but in my opinion it is better to use the CASE-WHEN so as to match other database engines like Microsoft SQL Server and Oracle.
SELECT
ItemCode,
Description,
IF (ApprovedQty = 0, OrderQty, ApprovedQty),
UoM,
UnitPrice,
Total
FROM table
I have an Access Form - lets call it "Add Labor" (Access 2007) that saves data into a table.
The table has two columns in particular called "Start Date" and "End Date" (This table stores tasks)
There is also another table called FiscalYears which includes Start and End Dates for Fiscal Years, which is structured as follows
FyID
FYear
StartDate
EndDate
Example Data:
FYId FYear StartDate EndDate
-----------------------------
1 2010 10/1/2009 9/30/2010
2 2011 10/1/2010 9/30/2011
So in My Add Labor Form if someone enters labor that span across two fiscal years I need to enter two labor entries. Here is an example
If a user selects Labor Start Date = 6/30/2009
And End Date 10/2/2010 , it spans two fiscal years
So in my Labor Table I should enter two things
LaborID StartDate EndDate
-----------------------------
1 6/30/2009 9/30/2010
2 10/1/2010 10/2/2010
Basically I need to do a check before I save the record and add two records if they span Fiscal years, right now I'm just blindly doing Save Record on the form (inbuilt), but I guess I need to add some VBA. I've hardly ever used Access so this may be simple(hopefully). I am thinking instead of the event which just calls Save Record, I need it to add custom VBA.
Say you have an unbound form for adding the dates, you can say:
Dim rsFY As DAO.Recordset
Dim rsAL As DAO.Recordset
Dim db As Database
Dim sSQL As String
Set db = CurrentDb
''Select all years from the fiscal years table
sSQL = "SELECT FYear, StartDate, EndDate " _
& "FROM FiscalYears WHERE StartDate>=#" & Format(Me.StartDate, "yyyy/mm/dd") _
& "# Or EndDate <=#" & Format(Me.Enddate, "yyyy/mm/dd") _
& "# ORDER BY FYear"
Set rsFY = db.OpenRecordset(sSQL)
Set rsAL = db.OpenRecordset("AddLabor") ''table
''Populate recordset
rsFY.MoveLast
rsFY.MoveFirst
Do While Not rsFY.EOF
''Add records for each year selected
rsAL.AddNew
If rsFY.AbsolutePosition = 0 Then
rsAL!StartDate = Format(Me.StartDate, "yyyy/mm/dd")
Else
rsAL!StartDate = rsFY!StartDate
End If
If rsFY.AbsolutePosition + 1 = rsFY.RecordCount Then
rsAL!Enddate = Format(Me.Enddate, "yyyy/mm/dd")
Else
rsAL!Enddate = rsFY!Enddate
End If
rsAL.Update
rsFY.MoveNext
Loop
If the code was running in a main form with a subform showing the Addlabor table, you could update the subform to show the new records like so:
Me.Addlabor_subform.Requery
Why do you need a FiscalYears table? If your organization's fiscal years always start on Oct. 1 and end on Sept. 30, you can use a function to determine the fiscal year for a given date.
Public Function Fy(ByVal pDate As Date) As Integer
Dim intYear As Integer
Dim intReturn As Integer
intYear = Year(pDate)
If pDate > DateSerial(intYear, 9, 30) Then
intReturn = intYear + 1
Else
intReturn = intYear
End If
Fy = intReturn
End Function
And simple functions to return the Start and End dates for a given year.
Public Function FyStart(ByVal pYear As Integer) As Date
FyStart = DateSerial(pYear - 1, 10, 1)
End Function
Public Function FyEnd(ByVal pYear As Integer) As Date
FyEnd = DateSerial(pYear, 9, 30)
End Function
You can then determine how many fiscal years are included in a given date range by:
Fy(EndDate) - Fy(StartDate)
But I may be totally off base because you said "Start Date = 6/30/2009 And End Date 10/2/2010" spans two years. However, this expression returns 2 (3 years):
Fy(#10/2/2010#) - Fy(#6/30/2009#)