I am attempting to use "%" in order to search for a range of dates. In the table the dates are of the format "03/01/2015" and I am trying to return data for all dates of a specific month (03/2015 for example).
I am creating two strings of the format...
String datePrev1 = monthLast + "%";
String datePrev2 = "%" + yearLast;
Where datePrev1 == "03%" and datePrev2 == "%2015" which I have confirmed to be generating correctly.
My SQL search method is...
SqlCommand selectCommand = new SqlCommand("SELECT project, prevWeekHours FROM submissionsHours WHERE (WWID = '" + ID + "' AND (datePrevWeek LIKE '" + datePrev1 + "' AND datePrevWeek LIKE '" + datePrev2 + "'))", Conn1);
Conn1.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
int totalTime = 0;
while (reader.Read() == true)
{
project.Add(reader[0].ToString());
projTime.Add(Convert.ToInt32(reader[1]));
totalTime += Convert.ToInt32(reader[1]);
}
Conn1.Close();
int index = project.Count; //total amount of projects
testLabel.Text = index.ToString() + "..." + datePrev1+datePrev2;
The testLabel.Text I have for troubleshooting is returning 0 for the index indicating there were no matches for this string when there are certainly entries in the table that should match it.
Any ideas on what I am doing wrong?
I have attempted querying like...
... WHERE datePrevWeek LIKE '03/__/2015';
... WHERE datePrevWeek LIKE '03____2015';
To no success... Thanks.
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND (YEAR(datePrevWeek)*100)+MONTH(datePrevWeek) = #YEARMONTH
#YEARMONTH should be of format 201503 representing march 2015.
Using parameters will avoid sql injection.
When datePrevWeek is varchar
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND right(datePrevWeek,7) = #YEARMONTH_STR
#YEARMONTH_STR is of format '01/2015'
Once you store dates in the format '2015-03-13',...
Plan A: WHERE dt LIKE '2015%'
Plan B (This is more efficient, given a suitable index):
WHERE dt >= CONCAT('2015', '-01-01')
AND dt < CONCAT('2015', '-01-01') + INTERVAL 1 YEAR
(I'm assuming '2015' is filled in by the code.)
Try Below:
Declare #Dat Date
set #Dat = '03/01/2015'
SELECT CAST(MONTH(#Dat) AS VARCHAR(2)) + '/' + CAST(YEAR(#Dat) AS VARCHAR(4)) AS [DD/YYYY]
Related
I have a problem with the filter of my datagridview. Currently, i'm applying 3 type of filter on date into my data (loaded by xml file) :
Month filter => This filter enable me to show all data relevant with the curent selected month
1 date filter => show all data which are associed to the current selected date
X dates filter => show all data which are associed to the current selected dates (31 max)
The filter is applied by seleting dates on a CalendarMonth control. The filter is actived on this method :
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime current_date = this.monthCalendar1.SelectionStart;
if (current_date.Month != this.old_Date.Month || current_date.Year != this.old_Date.Year)
{
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "DATE LIKE '*/" + current_date.ToString("MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.old_Date = current_date;
this.label_total.Text = this.calculateSum();
this.label_filter.Text = this.label_total.Text;
this.label_month.Text = current_date.ToString("MMMM (yyyy)");
}
else
{
if (this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy").Equals(this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy")))
{
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "DATE = '" + this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "'";
this.label_filter.Text = this.calculateSum();
}
else
{
System.Console.WriteLine("DATE >= '" + current_date.ToString("dd/MM/yyyy") + "' AND <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("DATE >= '" + this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "' And DATE <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
this.label_filter.Text = this.calculateSum();
}
}
}
The problem come when i have X selected dates. After selecting the date I have a strange bug. In fact, when i select 12/10 to 12/12 the filter show me the result of the october & november month ! The is no data for the december month a thoses dates.
Here a GIF of the problem :
the log for the filter say :
DATE >= '09/12/2015' AND <= '10/12/2015'
DATE >= '09/12/2015' AND <= '11/12/2015'
DATE >= '09/12/2015' AND <= '12/12/2015'
DATE LIKE '*/01/2016'
DATE LIKE '*/12/2015'
As we can see in the GIF the 2 other filters work fine. But the X selected dates didn't work like it is supposed to do ..
Anyone have an idea of the problem ?
For information :
Visual studio (community) 2015
C#
Windows Form
system in French (datetime in French, so => dd/MM/yyyy )
PS: sorry if the english ins't perfect.
Thank you.
What happens when you press December 21? If there's no results, then you should probably check the Locale of your DataTable and/or DataSet, that is the data source for your grid.
Is the result of the following code what you expected (dd/MM/yyyy)?
Console.WriteLine((this.dataGridView1.DataSource as DataTable).Locale.DateTimeFormat.ShortDatePattern);
I have found the bug ^^.
I used DATE column in String format and not in DateTime format. I have made all changes (in XML too) to work with DateTime value, and now the filter on X dates work fine !
Here the code of the new filtering method :
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime current_date = this.monthCalendar1.SelectionStart;
// we will identify if is the month/year who as changed or the day (to apply a filter on the data)
// month/year check
if (current_date.Month != this.old_Date.Month || current_date.Year != this.old_Date.Year)
{
// applying basic month & year filter (standard filter)
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "[DATE] >= '" + current_date.ToString("01/MM/yyyy") + "' AND [DATE] <= '"
+ DateTime.DaysInMonth(current_date.Year, current_date.Month).ToString() + current_date.ToString("/MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.old_Date = current_date;
this.label_total.Text = this.calculateSum();
this.label_filter.Text = this.label_total.Text;
this.label_month.Text = current_date.ToString("MMMM (yyyy)");
}
else
{
if (this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy").Equals(current_date.ToString("dd/MM/yyyy")))
{
//only one date is selected
// the day as changed
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "[DATE] = '" + current_date.ToString("dd/MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.label_filter.Text = this.calculateSum();
}
else
{
// more than 1 date is selected
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("[DATE] >= '" + current_date.ToString("dd/MM/yyyy") + "' AND [DATE] <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.label_filter.Text = this.calculateSum();
}
}
}
Thx for the help #Arie ;)
I wanted to display all rows and columns in my DB between specific dates on an aspx web. However, dates are not recorded in date or date time format. And it seems it is not possible to convert them to date format. I try to do this like this;
public DataTable DisplayRecord()
{
var reqID = Request.QueryString["MyId"].ToString();
//Date parsing
String[] ids = reqID.Split('-');
String date1 = ids[0];
String date2 = ids[1];
String provider = ids[2];
SqlDataAdapter Adp = new SqlDataAdapter("SELECT * FROM flightLogs WHERE depDate_depTime=CONVERT(date,depDate_depTime,104) AND depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104)", connection);
/*SqlDataAdapter Adp = new SqlDataAdapter("SELECT F.PNR, C.amount, F.provider, F.depDate_depTime FROM flightLogs F INNER JOIN companyLogs C ON F.PNR = C.PNR"+
" WHERE F.depDate_depTime=CONVERT(date,F.depDate_depTime,104) AND F.depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104) AND F.provider='" + provider + "' ORDER BY F.depDate_depTime ASC", connection);*/
DataTable Dt = new DataTable();
Adp.Fill(Dt);
FlightMonitor.DataSource = Dt;
FlightMonitor.DataBind();
return Dt;
}
But i get this error;
"Conversion failed when converting date and/or time from character string."
Also data in my DB is shown like this;
origin destination deptDate_depTime PNR flightno provider
KBP AMS 18.09.2015 - 17:35:00 5RQZ43 PS712 Amadeus
ATH FRA 10.07.2015 - 12:30:00 ZFY8XW PS716 PGS
it is a bad idea to store datetime values in varchar columns as you can see.
if you need a specific format, then you should convert it while you are about to display that value to the users.
but to make things working for now, you can change your where clause from this:
depDate_depTime=CONVERT(date,depDate_depTime,104)
to this:
depDate_depTime = convert(datetime, left(depDate_depTime, 10) + ' ' + right(depDate_depTime, 8), 104)
So I have been browsing stack overflow and MSDN and cannot find a control (or make sense of the ones I have) to access the data directly of a detailsview. I'm in C# using a .Net WebApplication.
I think what I am looking for is the equivalent in gridview is row.Cells[1].Value can anybody help with the accessor to the DetailsView cells?
What I am trying to do is to access the exact data values I have bound to the DetailsView1
.Text is sufficient for all the numbers and string (only two shown for example) but not for the timestamp MTTS (a datetime) as it lost the milliseconds and the code (SQL query) I use after it cannot find the correct values in the db without the milliseconds. Will I also need to change the way I have bound the data, or some setting to give the bound data millisecond accuracy?
Code example:
Decimal RUN_ID = 0;
DateTime MTTS = new DateTime();
foreach(DetailsViewRow row in DetailsView1.Rows)
{
switch(row.Cells[0].Text)
{
case "RUN_ID":
RUN_ID = Decimal.Parse(row.Cells[1].Text);
break;
case "MTTS":
MTTS = DateTime.Parse(row.Cells[1].ToString());
break;
}
}
I have tried
row.Cells[1].ID = "MTTS";
MTTS = (DateTime)((DataRowView)DetailsView1.DataItem)["MTTS"];
But it does not recognize the MTTS and I am not sure how to set the parameter I have tried a few different things already with no success.
The workaround was messy, essentially I rebuilt the query that gathered the data to the GridView and then I made a function to grab the MTTS directly using LinQ and the parameteres from inside the GridView which assigns the MTTS as a DateTime.
This was in my opinion a bad way of doing things but it worked. I would prefer a better solution.
MTTS = GetMTTS(JOB_PLAN, JOB_NAME,JOB_NAME_ID,RUN_ID,JOB_STATUS);
public DateTime GetMTTS(string JOB_PLAN, string JOB_NAME, string JOB_NAME_ID, Decimal RUN_ID, string JOB_STATUS){
string myEnvName = XXX;
TableName = XXX.ToString();
ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[myEnvName].ToString();
string thisRUN_ID = RUN_ID.ToString();
cmdText = #"SELECT MTTS FROM " + TableName +
" WHERE JOB_PLAN = '" + JOB_PLAN + "'"
+ " AND JOB_NAME = '" + JOB_NAME + "'"
+ " AND JOB_NAME_ID = '" + JOB_NAME_ID + "'"
+ " AND RUN_ID = '" + thisRUN_ID + "'"
+ " AND JOB_STATUS = '" + JOB_STATUS + "'";
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
try
{
SqlCommand SQLcc = new SqlCommand(cmdText,conn);
SqlDataReader reader;
reader = SQLcc.ExecuteReader();
while (reader.Read())
{
MTTS = reader.GetDateTime(0);
}
reader.Dispose();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
return MTTS;
}
I've looked at different links (like this one), but i still can't get where does this error message comes from. I keep on counting columns, comas and so on without finding where is the problem.
int exId = stride.getExerciseId();
string timestamp = stride.getTimeStamp();
int startSec = stride.getBeginningSec();
int startMsec = stride.getBeginningMSec();
int endSec = stride.getEndSec();
int endMSec = stride.getEndMSec();
float length = stride.getLength();
float duration = stride.getDuration();
float steplength = stride.getStepLength();
float stepDuration = stride.getStepDuration();
string supportingFoot = stride.getSupportingFoot();
string query = "INSERT INTO singlesupportstate (ExerciseId , TimeStamp , SingleSupportStateStartSeconds , SingleSupportStateStartMSeconds , SingleSupportStateEndSeconds , SingleSupportStateEndMSeconds , StrideLength , StrideDuration , StepLength , StepDuration , SupportingFoot)
VALUES("+ exId +",'" + timestamp +"',"+ startSec +"," + startMsec + "," + endSec + "," + endMSec + "," + length +"," + duration + "," + steplength + "," + duration + ",'" + supportingFoot + "')";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
EDIT :
So I changed my code in order to use Parameterized query, here is the new code that works:
if (this.OpenConnection() == true)
{
MySqlCommand cmd = connection.CreateCommand() ;
cmd.CommandText = "INSERT INTO singlesupportstate (ExerciseId , TimeStamp , SingleSupportStateStartSeconds , SingleSupportStateStartMSeconds , SingleSupportStateEndSeconds , SingleSupportStateEndMSeconds , StrideLength , StrideDuration , StepLength , StepDuration , SupportingFoot) "
+" VALUES(#exId,#timestamp,#startSec,#startMsec,#endSec,#endMSec,#length,#duration,#steplength,#stepduration,#supportingFoot)";
cmd.Parameters.Add("#exId", MySqlDbType.Int32);
cmd.Parameters.Add("#timestamp",MySqlDbType.Timestamp);
cmd.Parameters.Add("#startMsec",MySqlDbType.Int32);
cmd.Parameters.Add("#startSec",MySqlDbType.Int32);
cmd.Parameters.Add("#endSec",MySqlDbType.Int32);
cmd.Parameters.Add("#endMSec",MySqlDbType.Int32);
cmd.Parameters.Add("#length", MySqlDbType.Float);
cmd.Parameters.Add("#duration",MySqlDbType.Float);
cmd.Parameters.Add("#steplength",MySqlDbType.Float);
cmd.Parameters.Add("#stepduration", MySqlDbType.Float);
cmd.Parameters.Add("#supportingfoot", MySqlDbType.Text);
cmd.Parameters["#exId"].Value = exId;
cmd.Parameters["#timestamp"].Value = timestamp;
cmd.Parameters["#startMsec"].Value = startMsec;
cmd.Parameters["#startSec"].Value = startSec;
cmd.Parameters["#endSec"].Value = endSec;
cmd.Parameters["#endMSec"].Value = endMSec;
cmd.Parameters["#length"].Value = length;
cmd.Parameters["#duration"].Value = duration;
cmd.Parameters["#steplength"].Value =steplength;
cmd.Parameters["#stepduration"].Value =stepDuration;
cmd.Parameters["#supportingfoot"].Value =supportingFoot;
cmd.CommandTimeout = 120;
cmd.ExecuteNonQuery();
this.CloseConnection();
}
This means that in one of the values in the concatenation is breaking the INSERT because it has a comma or string delimiter, thus breaking the whole query string
Look at the actual query string after concatenation, before execution
And use parameters to remove this problem anyway and mitigate SQL injection risks.
The other option is a trigger (saym for audit or history) on the singlesupportstate table that has a broken INSERT too.
What is likely happening is one of two things:
1) There are ' quotes making your query seem it has fewer values, because it eats up the commas.
2) There are numbers being formatted with a comma rather than a point, resulting in the number 123.45 showing as 123,45, thus making the query think there are two integer values: 123 and 45 resulting in too many values.
As others have said, try and use query parameters and this won't happen again. It also saves you a lot of manual escaping of strings.
The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date