I'm looking for a one week interval, but any thing under 6 gives me:
timeIn > DATE_SUB(NOW(), INTERVAL 1 WEEK)
Error: Invalid attempt to Read when reader is closed.
timeIn > DATE_SUB(NOW(), INTERVAL 6 WEEK) //6 or anything above 6 and the query works
Error: Invalid attempt to Read when reader is closed.
Here's how I'm executing the query(this works, but when I change the INTERVAL from 6 to anything less I get the reader is closed error):
string sql = "SELECT rooms.building, rooms.room, " +
"users.FirstName, users.LastName, users.adUname, " +
"ingressegresslogs.timeIn, ingressegresslogs.timeOut, rooms.Id " +
"FROM rooms, users, ingressegresslogs " +
"WHERE ingressegresslogs.RoomId = rooms.Id " +
"AND ingressegresslogs.timeIn > DATE_SUB(NOW(), INTERVAL 6 WEEK) "
"AND ingressegresslogs.UserId = users.id " +
"ORDER BY rooms.Id ASC, ingressegresslogs.timeIn ASC";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
EDIT: This query works from the mysql command line for and INTERVAL 1 WEEK just not in the C# code. 428 rows with data are returned
Here is the reader code, which may be where the problem is.
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
if (!rdr.HasRows)
{
rdr.Close();
// EventLog.WriteEntry("IEReporter", "Database returned nothing", EventLogEntryType.Error, 234);
}
while (rdr.Read())
{
try
{
IELog queryResult = new IELog();
queryResult.RoomID = rdr.GetString("Id");
queryResult.FirstName = rdr.GetString("FirstName");
queryResult.LastName = rdr.GetString("LastName");
queryResult.ADUname = rdr.GetString("ADUname");
queryResult.Building = rdr.GetString("Building");
queryResult.Room = rdr.GetString("room");
queryResult.Ingresstime = rdr.GetDateTime ("timeIn");
// timeOut might be null
if (Convert.IsDBNull(rdr["timeOut"]))
{
queryResult.Egresstime = new DateTime(1111, 1, 11);
}
else
{
queryResult.Egresstime = rdr.GetDateTime("timeOut");
}
queryResultList.Add(queryResult);
}
catch (Exception ex)
{
Console.WriteLine("LogDAO build list: " + ex);
}
}
// Count rows
//Console.WriteLine("Row Count: {0}", queryResultList.Count);
rdr.Close();
return queryResultList;
Seeing the code you posted, you probably want to return immediately after you determine there are no rows.
if (!rdr.HasRows)
{
rdr.Close();
// EventLog.WriteEntry("IEReporter", "Database returned nothing", EventLogEntryType.Error, 234);
return; // do this, or otherwise skip the read below
}
The SQL works for me:
mysql> select DATE_SUB(NOW(), INTERVAL 1 WEEK);
+----------------------------------+
| DATE_SUB(NOW(), INTERVAL 1 WEEK) |
+----------------------------------+
| 2011-07-07 01:16:50 |
+----------------------------------+
Could it be your problem is that you are getting no rows returned, and that's why the reader is exploding?
Related
I have a mysql table with the columns ID, name, gold and timestamp.
This table shows with the following statement the average of the gold of the respective item(name). But now the database is already filled with 90k entries and the average should only be limited to 2 weeks. Here is the code:
`
private DataTable GetAverageGold()
{
var dtAverageGold = new DataTable();
var percentageBuy = double.TryParse(textBox1.Text.Replace("%", string.Empty), out var sell) ? sell / 100 : 0.02;
using (_con = GetMySqlConnection())
{
using (var cmd = new MySqlCommand(
"SELECT name AS name, FORMAT(GROUP_CONCAT(gold ORDER BY id DESC), 'de_DE') AS 'MOST RECENT', FORMAT(ROUND(AVG(gold) - AVG(gold) * " +
percentageBuy.ToString(CultureInfo.InvariantCulture).Replace(",", ".") +
"), 'de_DE') AS Einkaufspreis, FORMAT(ROUND(AVG(gold)),'de_DE') AS Durchschnitt, ROUND((AVG(gold) - GROUP_CONCAT(gold ORDER BY id DESC)) / GROUP_CONCAT(gold ORDER BY id DESC) * 100,2) AS 'profit in %' FROM items GROUP BY name ORDER BY Name",
_con))
{
try
{
_con.Open();
var reader =
cmd.ExecuteReader();
dtAverageGold.Load(reader);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString(), "Error in: GetAverageGold", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
_con.Close();
}
}
}
return dtAverageGold;
}
`
I tried "WHERE timestamp <= NOW() + INTERVAL 14 DAY GROUP BY name ORDER BY name" at the end of the statement. but it did not help. The syntax seems to be correct, as I get no error, but the average still refers to all entries
You were thinking along the right lines but it should have been -
WHERE timestamp >= NOW() - INTERVAL 14 DAY
or
WHERE timestamp >= CURRENT_DATE - INTERVAL 14 DAY
I need help how to get 3 months before expiration date alert. I used mysql.
Try
Call connection()
cmd.CommandText = "select * from medicine where expiry_date < date_sub(now(), interval 3 month)"
dr = cmd.ExecuteReader
count = 0
While dr.Read
count = count + 1
End While
If count = 1 Then
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "Medicine at Risk"
pop.AnimationDuration = 3000
pop.Popup()
Else
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "No items for risk"
pop.AnimationDuration = 3000
pop.Popup()
End If
Catch ex As Exception
End Try
I commented our Call Connection(). It is best to keep your connections local so you can be sure they are closed and disposed.
A Using...End Using block will accomplish this even it there is an error. Also I don't see where you associated a connection to your command. The call keyword is not necessary in this case. I assume that Connection() returns a connection but your did not provide a variable to hold the connection.
Pass the Select statement and the connection directly to the constructor of the command.
You have consumed all the data you returned in the While loop. If you only only need the Count then ask for the Count and use .ExecuteScalar.
I don't see the point of the If because the if portion is identical to the else portion.
An empty Catch just swallows errors. Bad idea.
Private Sub OPCode()
Dim CountReturned As Integer
Try
'Call Connection()
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand("select Count(*) from medicine where expiry_date < date_sub(now(), interval 3 month);", cn)
cn.Open()
CountReturned = CInt(cmd.ExecuteScalar)
End Using
End Using
If CountReturned = 1 Then
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "Medicine at Risk"
pop.AnimationDuration = 3000
pop.Popup()
Else
pop.Image = Image.FromFile("E:\asasda.png")
pop.TitleText = "Notification Alert!!!"
pop.ContentText = "No items for risk"
pop.AnimationDuration = 3000
pop.Popup()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
If you cannot get the MySql data_sub working then use vb and parameters.
Using cmd As New MySqlCommand("select Count(*) from medicine where expiry_date < #Minus3Months;", cn)
cmd.Parameters.Add("#Minus3Months", MySqlDbType.DateTime).Value = Now.AddMonths(-3)
cmd.CommandText = "select * from medicine where expiry_date < #threeMonthsAgo"
cmd.parameters.add("#threeMonthsAgo", variableWithYourDate)
You can pass in a value from VB using parameters.
I am using HQL with DATE_ADD (mysql function) as below
String hql =
"select count(*) " +
"from ProgramGroupEvent as eventLog " +
"where eventLog.id= :id" +
"and DATE_ADD( eventLog.eventDate, INTERVAL :interval MINUTE) > now()";
long count = 0;
try {
count = ((Long)sess.createQuery( hql )
.setLong( "id", id)
.setInteger("interval", interval )
.iterate().next()).longValue();
} catch (HibernateException e) {
e.printStackTrace();
}
But hibernate throws a token error as below
antlr.NoViableAltException: unexpected token: :
at org.hibernate.hql.internal.antlr.HqlBaseParser.identPrimary(HqlBaseParser.java:4016) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
at org.hibernate.hql.internal.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:859) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
at org.hibernate.hql.internal.antlr.HqlBaseParser.atom(HqlBaseParser.java:3390) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
PS: I am using Hibernate 4.1.7
I did further research and found out the issue. The problem is Hibernate is not able parse the syntax. As per it's expectation, this is not well formed HQL syntax.
https://forum.hibernate.org/viewtopic.php?f=1&t=982317&view=previous
I fixed by replacing
DATE_ADD( eventLog.eventDate, INTERVAL :interval MINUTE) > now()";
With
time_to_sec(timediff( now() , eventLog.eventDate )) < :seconds";
Hopefully, this can help for someone
Your query require two parametrs
pharmacyOid
interval
But in your query parameters id and interval are used.
Your query should look:
count = ((Long)sess.createQuery( hql )
.setLong( "pharmacyOid", id)
.setInteger("interval", interval )
.iterate().next()).longValue();
Good day I have written a function that needs to limit the number of employees that can be added to the database.
<WebMethod()>
Public Function EmployeeSubToken()
Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
Dim subtype = "vchSubscriptionType"
Dim Token
Select Case subtype
Case subtype = "Bronze"
Token = 1
Case subtype = "Silver"
Token = 2
Case subtype = "Gold"
Token = 3
Case subtype = "Platinum"
Token = 4
End Select
Dim cmd2
Select Case Token
Case Token = 1
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
Case Token = 2
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
Case Token = 3
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
Case Token = 4
cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
End Select
End Function
Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?
if you want to limit the inserts, have a function that will query your database and return a count of rows, SELECT COUNT(*) FROM dtEmployment ; then just use a simple if,
if(dtEmploymentCount < MydesiredCount) then
'Do My Insert
else
'Return your message (Maximum amount of entries reached)
end If
maybe TOP(5) your looking for.
is there any order to the rows your returning, i.e. does it matter which 5 are returned?
i am totally stuck with this error, please do help me..
i create a json file, user can select from start date to end date..
so button1 function as to generate the file..
the program goes well until i select a larger data to generate.. then this memory error comes out.. Here is my code:
Using writer As JsonWriter = New JsonTextWriter(sw)
writer.Formatting = Formatting.Indented
With writer
.WriteStartObject()
.WritePropertyName("LiveValue")
.WriteStartArray()
Do
liveValue.Time_Stamp = u
liveValue.Current = Generator.Next(MyMin_Current, MyMax_Current + 1)
liveValue.Voltage = Generator.Next(MyMin_Voltage, MyMax_Voltage + 1)
liveValue.Power = liveValue.Current * liveValue.Voltage
.WriteStartObject()
.WritePropertyName("ID")
.WriteValue(i)
.WritePropertyName("TimeStamp")
.WriteValue(liveValue.Time_Stamp)
.WritePropertyName("MotorID")
.WriteValue(liveValue.MotorID)
.WritePropertyName("Current")
.WriteValue(liveValue.Current)
.WritePropertyName("Voltage")
.WriteValue(liveValue.Voltage)
.WritePropertyName("Power")
.WriteValue(liveValue.Power)
.WriteEndObject()
i = i + 1
If liveValue.MotorID < 20 Then
liveValue.MotorID = liveValue.MotorID + 1
Else
liveValue.MotorID = 1
End If
'If endTime > startTime Then
' liveV.Time_Stamp = u.AddMinutes(+1)
'Else
' liveV.Time_Stamp = endTime
'End If
'(Time Stamp) Time changed every 7secs
If i = w Then
u = u.AddMinutes(+1)
w = w + 20
End If
Loop Until (liveValue.Time_Stamp = endTime)
.WriteEndArray()
.WriteEnd()
End With
file1.WriteLine(sb.ToString)
pBar.Style = ProgressBarStyle.Continuous
End Using
please do help me to solve it..Thank you