I'm attempting to compare an endDate column in a SQL Server database to a stored variable called highDate in c#.
DateTime highDate = new DateTime(2999, 1, 1);
SqlConnection myConnection = new SqlConnection("My connection string");
SqlCommand myCommand = new SqlCommand("My query including endDate_TS", myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
DateTime endDate = new DateTime(myReader["endDate_TS"]); //something is wrong here
}
if (endDate > highDate)
{
//do something
}
How do I correctly format the endDate variable I created to accept the endDate_TS from the SQL Server database? (the endDate_TS is a SQL Server DATETIME datatype)
DateTime has several constructors but none which takes an object. But myReader["endDate_TS"] returns an object. If it's actually the number of ticks (what it seems to be if _TS means TimeSpan) you can use the constructor that takes a long:
int indexOfEndDateTsColumn = myReader.GetOrdinal("endDate_TS");
DateTime endDate = new DateTime(myReader.GetInt64(indexOfEndDateTsColumn));
However, the last sentence in parentheses suggests that it's actually a datetime in the database, then you can use DataReader.GetDateTime directly:
DateTime endDate = myReader.GetDateTime(indexOfEndDateTsColumn);
Related
I have a table of data in Access
DateTimeLog has date/time datatype while the other rest are string.
I need to get the total number of row of data at the last hour of system date with specified ModelLog. But I could not think of a correct structure of the query using MS Access as I am very new to MS Access.
Below shows how I insert the data:
DateTime now = DateTime.Now;
var today = now.ToString("g");
DateTime d = DateTime.Parse(today);
const string sql = #"INSERT INTO timer(DateTimeLog, ShiftLog, CTLog, WorkcellLog, ModelLog, StationLog)VALUES(#d, #shift, #ct, #wc, #wm, #ws)";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#d", OleDbType.DBTimeStamp).Value = d;
cmd.Parameters.Add("#shift", OleDbType.VarChar).Value = shiftlb.Text;
cmd.Parameters.Add("#ct", OleDbType.VarChar).Value = timerlb.Text;
cmd.Parameters.Add("#wc", OleDbType.VarChar).Value = wclb.Text;
cmd.Parameters.Add("#wm", OleDbType.VarChar).Value = mlb.Text;
cmd.Parameters.Add("#ws", OleDbType.VarChar).Value = slb.Text;
try
{}
catch(exception e)
{}
Ok, so you clearly know how to run a database query with parameters, you just need to run this query as ExecuteScalar, casting the result to an int
SELECT COUNT(*) FROM timer WHERE dateTimeLog >= #d
And then set your d parameter to an hour ago
cmd.Parameters.Add("#d", OleDbType.Date).Value = DateTime.Now.AddHours(-1);
Side note I would recommend not round tripping via string just to cut the seconds off a time. Instead consider:
var d = DateTime.Now;
d = d.AddTicks( -(d.Ticks % (60*TimeSpan.TicksPerSecond)));
Or maybe
var d = DateTime.Now;
d = d.AddMilliseconds(-d.Milliseconds).AddSeconds(-d.Seconds);
I found out another way of getting the number of data within the same hour. Create two new columns, HourID and TodayDate both represent current hour in 24hours format and today's date respectively. Insert the data accordingly.
Getting count of data:
const string sql = #"SELECT COUNT(*) FROM timer WHERE HourID = #h AND TodayDate = #td AND ModelLog = #m";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#h", OleDbType.VarWChar).Value = DateTime.Now.ToString("%H");
cmd.Parameters.Add("#td", OleDbType.VarWChar).Value = DateTime.Now.ToShortDateString();
cmd.Parameters.Add("#m", OleDbType.VarWChar).Value = mlb.Text;
How do you compare C# now to SQL Server datetime?
I have tried ten things, but nothing works:
string sql;
DataTableReader dr;
sql = "Select StartDate from mytable";
SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.AppSettings["DB"]);
DataTable dt = new DataTable();
da.Fill(dt);
dr = dt.CreateDataReader();
var now = DateTime.Now.Date;
while (dr.Read())
{
// StartDate datatype is a SQL Server datetime and possibly can be null
if(dr["StartDate"] < now)
{
// code for start date is in the past
}
}
You have to convert SQL Server string to datetime.
// StartDate datatype is a SQL Server datetime and possibly can be null
if(Convert.ToDateTime(dr["StartDate"]) < now)
{
// code for start date is in the past
}
How to store date as "1" and month as "1" to mysql database by using c#,(for example 1-1-1987),i can get year from the variable frdt,so i need to store for example 1-1-frdt.
string frdt = drow1["release_year"].ToString();
i would pass it into a DateTime object and insert that one into your database
string frdt = drow1["release_year"].ToString();
DateTime Result = new DateTime(int.Parse(frdt), 1, 1);
string Command = "INSERT INTO TABLENAME (COLUMNNAME) VALUES (#DATEVALUE);"; // TODO
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand myCmd = new MySqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("#DATEVALUE", Result);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
If you're storing a date then it should be stored as a binary date, not as text. It's hard to tell whether you're doing that or not but you absolutely should. The fact that you're storing a year, which is a number, in a string variable is not encouraging. You should be storing the year in an int and then creating a DateTime like so:
var myDate = new DateTime(year, 1, 1);
where year is the int containing the year. You then save that to your database as you would any other data, using a parameter one would hope, e.g.
var command = new MySqlCommand("UPDATE MyTable SET MyDate = #MyDate WHERE ID = #ID", connection);
command.Parameters.AddWithValue("#MyDate", myDate);
I need to call a query between dates
class MemberSched
{
static DataTable GetMemberRecords(DateTime date, DateTime date2)
{
var connSettings = ConfigurationManager.ConnectionStrings["MyDB"];
{
string CN = connSettings.ConnectionString;
MySqlConnection conn = new MySqlConnection(CN);
MySqlCommand cmd = new MySqlCommand("select value 1, value 2, value 3, value 4 from sometable where datefrom >= CAST(#startDate AS DATE) and dateto <= CAST(#endDate AS DATE)", conn);
cmd.Parameters.AddWithValue("#startDate", date);
cmd.Parameters.AddWithValue("#endDate", date2);
MySqlDataAdapter data = new MySqlDataAdapter(cmd);
conn.Open();
DataTable dt = new DataTable();
data.Fill(dt);
return dt;
}
}
}
public object QueryBetweenDate()
{
DataTable table = GetMemberRecords();
return table;
}
private void datePicker_ValueChanged(object sender, EventArgs e)
{
//i don't know what should i put in here
}
private void datePicker2_ValueChanged(object sender, EventArgs e)
{
//i don't know what should i put in here
}
i'm stumped over this, as i'm still new in C#, my query works fine as i have tried it in mysql beforehand, the date arguments on GetMemberRecords i dont know if that is right and also im getting error on public object QueryBetweenDate()
Your SQL is close, but not quite. Try this:
select value 1, value 2, value 3, value 4 from sometable where datefrom BETWEEN #startDate and #endDate
You shouldn't have to cast the datetime variables since the connector will automatically do it as long as you pass in DateTime objects to the parameters. The BETWEEN SQL operator then takes care of making sure it is between the right dates.
Other than the casts, there wasn't anything technically wrong with the original SQL, but BETWEEN is a little easier to understand.
I have a string date in database. I did like below mentioned format but it shows error like
input string was not in a correct format
But when I referred with internet this method is correct but it does not work for me. Let me know the reason?
string str1 = "select todate from Employee where EmpCode='" + code + "'";
SqlDataReader dr1 = conn.query(str1);
if (dr1.Read())
{
string todate1 = dr1[0].ToString();
int todate2 =Convert.ToInt32(todate1);
}
It sounds like you should be using a DateTime column in the database, at which point there's no need for integers or strings:
var today = DateTime.Today; // Or maybe use DateTime.Now
// Use parameterized SQL rather than string concatenations
string sql = "select todate from Employee where EmpCode=#EmpCode";
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = code;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
DateTime date = reader.GetDateTime(0);
if (today > date)
{
// Do something
}
}
}
}
}
If your date really is being stored as a string and you can't change that (and if you can, then definitely do so), you can use DateTime.ParseExact instead:
// Other code as before
while (reader.Read())
{
DateTime date = DateTime.ParseExact(reader.GetString(0),
"yyyy-MM-dd", // Or whatever the format is
CultureInfo.InvariantCulture);
if (today > date)
{
// Do something
}
}
Note that in both cases, this uses the system local time zone. You may want to consider storing all values in UTC, and performing all calculations that was as well - in which case you can use DateTime.UtcNow.