How to compare C# now to SQL Server datetime - c#

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
}

Related

Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01830: date format picture ends before converting entire input string'

I ma getting an error
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01830: date format picture ends before converting entire input string'
while finding out volume through a c# code and oracle query:
public DataTable empcount(string strtdate, string enddate)
{
string cString = ConfigurationManager.ConnectionStrings["greft"].ToString();
OracleConnection conn = new OracleConnection(cString);
OracleCommand cmd2 = new OracleCommand();
cmd2.CommandText = "Select (sum(emp)) from emp_rec where emp_typ = 'M'and emp_stat!= 'ON'and trunc(join_start) >= TO_CHAR(TO_DATE(:sdate, 'DD-MM-YY'), 'DD-MON-YY') and trunc(join_end) <= TO_CHAR(TO_DATE(:edate, 'DD-MM-YY'), 'DD-MON-YY') ";
cmd2.Parameters.Add(":sdate", strtdate);
cmd2.Parameters.Add(":edate", enddate);
cmd2.Connection = conn;
OracleDataAdapter da = new OracleDataAdapter(cmd2);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Dispose();
return dt;
}
In the table the join_start and join_end has date in the format like '02-MAY-2019'. The :sdate & :edate input will be in the format of mm/dd/yyyy (e.g. 05/01/2019).
The column REQ_START_TIME is of data type VARCHAR2(11) with values such as 02-MAY-2019
The parameter value sdate is a String with values such as 05/01/2019
I see two problems
Trunc on a character column
trunc(REQ_START_TIME) - you should convert the string to DATE before truncating it (or even better store the value in a DATE column!)
Mask 'DD-MM-YY' for the value 05/01/2019
Convert the predicate to
where trunc(to_date(REQ_START_TIME,'DD-MON-YYYY')) >= TO_DATE(:sdate, 'DD/MM/YYYY')
Generall recommendation - do not store a DATE values in a character column in the database

No data is showing in combobox

I am trying show some data from a database to a combobox based on another combobox selection with this code:
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
#"Select [LedId],[LedName] from [Ledger] where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?
change your SQL statement as below(Date is reserved keyword)
string sql =
#"Select [LedId],[LedName] from [Ledger] where [Date] >= #prmStartDate and [Date] <= #prmEndDate";
You need to give table name when you fill dataset since you are using the name when you set data source
da.Fill(dt, "Ledger");
or set the data source as below
VoucherLedgerName_combo.DataSource = dt.Tables[0];
DataRow dr = dt.NewRow();
dr["Ledger"] = "--Select All--";
dt.Rows.InsertAt(dr, 0);
You can change from
da.Fill(dt);
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
to
da.Fill(dt, "Ledger");
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"].DefaultView;
else
VoucherLedgerName_combo.DataSource = dt.Tables[0].DefaultView;
or
VoucherLedgerName_combo.DataSource = dt;

Invalid column name on adapter fill

I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.

C# Updating mySQLDateTime Datatable

I'm having trouble updating a mySQL database with a datatable. I can do it with an INSERT statement, but the table fails the assignment when I insert a row with the error "Couldn't store <...> in date Column. I have millions of records to insert and I thought this way might be faster. I actually don't care about the time, just the date.
MySqlConnection con = new MySqlConnection();
con.ConnectionString = string.Format(#"server={0};userid={1};password={2};database={3};AllowZeroDatetime=True", srvr, user, pass, db);
MySqlCommand cmnd = new MySqlCommand();
cmnd.Connection = con;
con.Open();
cmnd.CommandText = "DROP TABLE IF EXISTS dateTest";
cmnd.ExecuteNonQuery();
cmnd.CommandText = "CREATE TABLE dateTest (date DATE, dateTime DATETIME)";
cmnd.ExecuteNonQuery();
string myDate = "2014-04-19";
string myDateTime = "2014-04-20 00:00:00";
//this code works
cmnd.CommandText = string.Format("INSERT INTO dateTest(date, dateTime) VALUES('{0}', '{1}')", myDate, myDateTime);
cmnd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * from dateTest", con);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
DataTable tbl = new DataTable();
da.Fill(tbl);
foreach (DataRow row1 in tbl.Rows)
{
Debug.WriteLine(string.Format("{0} : {1}", row1["date"], row1["dateTime"]));
//returns: 4/19/2014 : 4/20/2014 12:00:00 AM
}
DataRow row2 = tbl.NewRow();
row2["date"] = myDate; //Errors here: Couldn't store <2014-04-19> in date Column. Expected type is MySqlDateTime.
row2["dateTime"] = myDateTime; //Also errors here: Couldn't store <2014-04-20 00:00:00> in dateTime Column. Expected type is MySqlDateTime.
tbl.Rows.Add(row2);
da.Update(tbl);
this is my first time trying to answer a question. Hope this help.
I think you have to convert the date to DateTime first before you can store it in mysql.
string myDateTime = "2014-04-20 00:00:00";
DateTime myDateTimeValue = DateTime.Parse(myDateTime);
Then
row2["dateTime"] = myDateTimeValue;
I have not tried it yet. Hope it works

Pulling dateTime from SQL Server database

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);

Categories