Trying to retrieve records by passing date in where condition, i am sending date by using date time picker but at the end reader not showing any record.
I did conversion of date time as Convert(char(10),ext_date,101) still facing the same problem.
string str=#"select * from extra_expense where CONVERT(char(10),ext_date,101) = #date";
sqlcommand = new SqlCommand(str,sqlconnection );
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetimepicker1.value);
datareader = sqlcommand.ExecuteReader();
List<Projects> projects = new List<Projects>();
while (datareader.Read())
{
Projects proj = new Projects();
proj.expenseid = Convert.ToInt32(datareader.GetValue(0));
proj.ProjectDate = Convert.ToDateTime(datareader.GetValue(1));
projects.Add(proj);
}
datareader.Close();
return projects;
You can specify dates as strings in T-SQL, like so:
SELECT MyFields FROM MyTable
WHERE StartDate >= '01-01-00' AND StartDate <= '12-31-00'
You shouldn't cast the field in the table, you should cast the parameter to the correct type. In fact, you are already casting it because the parameter is declared as datetime, but on your query you are forcing ext_date to char(10).
Try this:
string str=#"select * from extra_expense where ext_date = #date";
along with
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetime.Parse( datetimepicker1.value);
Related
I want to extract DATE and TIME into two different variables that can be used to display in text boxes.
Here is what I am doing in my code -
MySqlCommand cmd3 = new MySqlCommand();
MySqlDataReader reader2 = null;
cmd3.CommandText = "SELECT lastlogintime from authentication where email=#email";
cmd3.Parameters.AddWithValue("#email", LoggedInUser);
cmd3.Connection = connect;
reader2 = cmd3.ExecuteReader();
while (reader2.Read())
{
string temp = reader2.GetString(reader2.GetOrdinal("lastlogintime"));
lastloginDateTB.Text = temp.ToString(); // This will give full string as (yyyymmdd HH:mm:ss) into lastloginDateTb
// Now I want to display date in Date_TB and Time in Time_TB. Note: I have 2 different textboxes as lastloginDateTB & lastloginTimeTB ;
}
This code extract value from authentication table (lastlogintime column) into temp variable and displays the same in lastloginDateTB textbox but I want to display specific date and time in each of its column.
Note: Table consist of fieldname - lastlogintime which has DATETIME value.
Simply convert the string to DateTime and extract date using ToShortDateString() method and Time using ToShortTimeString() method
Try this:
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm");
dt.ToString("hh:mm tt");
dt.ToString("H:mm");
dt.ToString("h:mm tt");
string date = dateTime.Date.ToString(); //for date
I have a column named compare_time(datatype: DateTime) in database. Its value is inserted as 3/8/2017 12:09:08 AM. Now in c# I want to write a query to compare if this column value is equal to Singapore's current date time.(Only need to compare the date.). Current Singapore date time is get as 08-03-2017 PM 03:35:11.
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM time_details where compare_time='"+dt+"' ", con1);
Please help to correct the where clause.
The first step is to not compare the dates using automatic string conversion but use a parameter.
Still this is not enough because your DateTime variable contains also the time part as well the database column. So you need to isolate the date part both on the database data and in the variable
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter(#"SELECT * FROM time_details
where Convert('Date',compare_time) = #date", con1);
adapter.SelectCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dt.Date;
....
In this way you don't let the compiler decide which is the right string 'format' that is correct for Sql Server to understand your query.
Instead you pass the DateTime variable as a Date (using the Today property which doesn't have a meaningful time part) to the database engine that now has all the info to make the correct comparison.
Notice that this approach could not be the most efficient one. That CONVERT inside the WHERE clause could wreak havoc with your indexes. Probably you could use a different approach
string cmdText = #"SELECT * FROM time_details
where compare_time >= #init AND
compare_time < #end";
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, con1);
adapter.SelectCommand.Parameters.Add("#init", SqlDbType.DateTime).Value = dt.Date;
adapter.SelectCommand.Parameters.Add("#end", SqlDbType.DateTime).Value = dt.Date.AddDays(1);
I have a database with a datatable which includes a DateTime column among other things. When using SQL server, I could read the DateTime value from the database using the following code:
SqlCommand getdate = new SqlCommand("SELECT * FROM EMPinfo WHERE id = #employeeId", connect);
getdate.Parameters.AddWithValue("#employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
getdate.Connection = connect;
connect.Open();
SqlDataReader readList = getdate.ExecuteReader(CommandBehavior.CloseConnection);
while (readList.Read())
{
lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
}
After changing the code to run with SQLite:
SQLiteConnection connect = new SQLiteConnection(#"Data Source=quotevodata.db;");
SQLiteCommand getlistname = new SQLiteCommand("SELECT * FROM EMPinfo WHERE id = #employeeId", connect);
getlistname.Parameters.AddWithValue("#employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
getlistname.Connection = connect;
connect.Open();
SQLiteDataReader readList = getlistname.ExecuteReader(CommandBehavior.CloseConnection);
while (readList.Read())
{
lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
}
I keep getting the following error: "String was not recognized as a valid datetime."
I've tried different combinations and declaration of variables but it's not working out. What is the correct configuration to read DateTime values out of an SQLite database?
SQLite does not have a built-in DateTime object, but rather stores them as Text, Real, or Int values.
From your error, you can infer that it's outputting as text; Which according to SQLite documentation should be in the format of "YYYY-MM-DD HH:MM:SS.SSS"
There are various ways you could parse this to a DateTime object, but I'll use RegEx:
public static DateTime ConvertToDateTime(string str)
{
string pattern = #"(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})";
if (Regex.IsMatch(str, pattern))
{
Match match = Regex.Match(str, pattern);
int year = Convert.ToInt32(match.Groups[1].Value);
int month = Convert.ToInt32(match.Groups[2].Value);
int day = Convert.ToInt32(match.Groups[3].Value);
int hour = Convert.ToInt32(match.Groups[4].Value);
int minute = Convert.ToInt32(match.Groups[5].Value);
int second = Convert.ToInt32(match.Groups[6].Value);
int millisecond = Convert.ToInt32(match.Groups[7].Value);
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
else
{
throw new Exception("Unable to parse.");
}
}
docs: http://www.sqlite.org/datatype3.html
Thanks for the answers, I finally got it to work by changing the INSERT statement to SQLite format as suggested:
string empDob = dateDOB.Value.ToString("yyyy-MM-dd");
//I then inserted this string into the database with the column configured as a "DATE" datatype.
After that, I used the following statements to read and format the date to usable string and it worked beautifully:
DateTime dateOfBirthEmp = DateTime.Parse(readList["dob"].ToString());
lblEmpDob.Text = dateOfBirthEmp.ToString("d");
I really appreciate the help.
Why do you convert 2 times?
If you have a Date column in SQLite the provider can manged that for you.
You can direct insert as DateTime and read as DateTime.
It's feels a bit hacky but this is the only solution I was able to come up with.
It just creates a new column, copies all the values in DateTime format to the new column and deletes the old time string column.
DataTable dt = GetDataTable();
string tc = "TimeColumnName";
dt.Constraints.Clear();
int ordinal = dt.Columns[tc].Ordinal;
dt.Columns[tc].ColumnName = "TSOLD";
dt.Columns.Add(tc, typeof(DateTime));
foreach (DataRow row in dt.Rows) row[tc] = Convert.ToDateTime(row["TSOLD"]);
// remove "OLD" column
dt.Columns.Remove("TSOLD");
dt.Columns[tc].SetOrdinal(ordinal);
dt.Constraints.Add(new UniqueConstraint(dt.Columns[tc]));
I have to following parameters that are necessary to execute a stored procedure in sql server 2008 r2
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment.ToString());
These are necessary to execute a stored procedure. All of the session variables are passed correctly. However when the gridview renders it shows no data. I know there is data because I can run the stored procedure on SSMS and it runs perfectly with the parameters that are passing to the proc (when I input them).
I am pretty confused at this point so any help would be helpful.
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
ENTIRE ROUTINE: (maybe this will help)
public void ExecuteDetailReport()
{
string sessionConnection = Session["Company"].ToString();
string sessionStartDate = Session["StartDate"].ToString();
string sessionEndDate = Session["EndDate"].ToString();
string payment = Session["payment"].ToString();
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings[sessionConnection].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("dbo.cusGenDenialReportPivotStylePType", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
/*da.SelectCommand.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.VarChar, 11)).Value = sessionStartDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.VarChar, 11)).Value = sessionEndDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#PaymentType", SqlDbType.VarChar, 100)).Value = payment.ToString();*/
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate);
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment);
lblTest.Visible = true;
lblTest.Text = "You selected " + payment + ".";
DataSet ds = new DataSet();
da.Fill(ds, "DetailDenial");
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
da.Dispose();
conn.Close();
}
I think your issue is related to the fact that you are using and comparing dates as strings and not dates. Your result set is empty because your query is trying to compare date strings alphabetically instead of chronologically. To refactor your code, I would make sure that you address the following areas:
Setting the session variables
Carefully parse the dates out of your text fields.
DateTime startDate;
if (DateTime.TryParseExact(txtStartDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate))
{
Session["StartDate"] = startDate;
}
DateTime endDate;
if (DateTime.TryParseExact(txtEndDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out endDate))
{
Session["EndDate"] = endDate;
}
You may want to handle the case when the TryParseExact methods return false (parse failure).
Retrieving session variables
We set the session variables as DateTime objects, so cast them back upon retrieval:
var sessionStartDate = (DateTime)Session["StartDate"];
var sessionEndDate = (DateTime)Session["EndDate"];
Notice we're still using native .NET types here.
Setting up your query parameters
Use the .Date property of the DateTime struct to drop the time component:
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.Date);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.Date);
...
And lastly, update your stored procedure so that its parameters are of type date:
CREATE PROCEDURE dbo.cusGenDenialReportPivotStylePType
(
#StartDate date = null,
#EndDate date = null,
...
)
AS
...
SELECT
*
FROM
Somewhere
WHERE
TheDate BETWEEN #StartDate AND #EndDate
Keeping everything in its native data format will make your life a lot easier.
Remove .ToString() calls from your code.
I'm trying to write code on c# that will compare between date that i have on SQL table (table:items, column "endTime") against datetime.now and by the result - display image.
example:
if the time on the column table is before the time now.. so display on the aspx image1, else display image2.
i've tried to do that by sql command:
private DateTime endTime(out int lastDate)
{
SqlConnection connection = new SqlConnection("Data Source=******;Initial Catalog=******;User ID=*****;Integrated Security=False;");
string commandtext = "SELECT TOP(1) endTime FROM items";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
SqlCommand command2 = new SqlCommand(commandtext, connection);
lastDate = (int)command2.ExecuteScalar();
connection.Close();
return ...
}
but i have problem with the return, and with the execution of the method... :
int d;
Console.WriteLine(endTime(out d));
if (d < DateTime.Now)
{
image1.Visible = true;
}
else
{
image2.Visible = true;
}
Console.WriteLine(d);
but i got error, but i believe it's come from the return.
Instead of if (d < DateTime.Now) use this: if (d < DateTime.Now.Date)
Shouldn't you be casting out a DateTime from your query and not an int? Also, the stack trace/debugger should give you the line number of the exception. Can you post the stack trace?
What is returned by your sql query (I believe ticks)?
How do you convert int into DateTime, show a code please
Enclose SqlConnection in using() block as shown below:
using (SqlConnection connection = new SqlConnection(...))
i would suggest letting the database do the date comparison right in the sql.
SYSDATE can be compared to EndTime right in the query, and you can either not bring back rows that dont match (which allows you to process every row in the result set equally) or you check a simple value in the return set to see if the time is in the right period.