I'm building an application that stores a group of datetimes to keep track of when I print a particular report. The report is built up of information from a second table that also has datetimes. I'm trying to get the report to populate a datagridview with records that are only after the last datetime in the first table.
The first table is called 'deliverylog', this table stores the past print dates. The second table is called 'joblog', and it stores the records of previous job entries.
When I run the program, it works just fine and populates the gridview with all records after the last date, but it's not refined... it only populates with dates after the date and not the time. I need the query to populate the gridview to the second....
DateTime lastDeliveryDate;
private void getLastDelivery() // Sets global variable lastDeliveryDate to the last timestamp entered in the deliverylog table
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT TOP 1 * FROM deliverylog ORDER BY Id DESC", logConn);
drLogSet = command.ExecuteReader();
while (drLogSet.Read())
{
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
private void populateGridView()
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT * FROM joblog WHERE TimeStamp > #date", logConn);
command.Parameters.AddWithValue("#date", lastDeliveryDate);
dtLogSet = new DataTable();
bsLogSet = new BindingSource();
daLogSet = new SqlCeDataAdapter(command);
cbLogSet = new SqlCeCommandBuilder(daLogSet);
daLogSet.Fill(dtLogSet);
bsLogSet.DataSource = dtLogSet;
dataGridView1.DataSource = bsLogSet;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
Anyone know how to get the this working right? I'm storing the timestamps for both tables as datetime data types and in the following format: "MM/dd/yyyy hh:mm:ss tt"
I believe that using the AddWithValue method is internally converting the value and probably loosing the desired time precision. Instead, use the Add(String, SqlDbType) method overload of the Parameters collection:
var dateParameter = command.Parameters.Add("#date", SqlDbType.DateTime);
dateParameter.Value = this.lastDeliveryDate;
Make sure you have the correct value before setting the parameter value by inspecting the variable using the debugger.
And you could try using the DATEDIFF SQL function instead of the > operator to ensure proper precision:
SELECT * FROM joblog WHERE DATEDIFF(second, #date, TimeStamp) > 0
The problems is probably this line:
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
Assuming your TimeStamp field is a datetime type, you should use:
lastDeliveryDate = (DateTime) drLogSet["TimeStamp"];
Please confirm the data type of your TimeStamp field.
You should format the date to yyyyMMdd hh:mm:ss.
lastDeliveryDate.toString("yyyyMMdd hh:mm:ss").
In this postare more details.
How to compare sqlite TIMESTAMP values
Related
I have a table column as status(Varchar,records "Paid"/"Unpaid" only) and another column as nextDateOfPay(datetime, records a date).I need to update this status column as Unpaid for the records which are as Paid when the date(present date) is passed the date in nextDateOdPay column.And I need to repeat this update for every row in the table. Primary key is Id column(integer).
I have no clue where to start,do i need to use T-sql or if i have to use sql agent job.I'd like to know if there is a simple solution that i can write in the program itself.Thank you so much in advance !
Code so far is as,
dateTimePicker3.Value = DateTime.Now;
textBox12.Enabled = false;
string newstat;
string query = "select Id,nextDateOfPay from gymTb where status='Paid'";
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, cn);
DateTime x = DateTime.Now;
DateTime y;
if (cn.State.ToString() == "Closed")
{
cn.Open();
}
try
{
object dtx = cmd.ExecuteScalar();
y = Convert.ToDateTime(dtx);
int result = DateTime.Compare(x, y);
if (result >= 0)
newstat = "Unpaid";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
A simple UPDATE query would do:
UPDATE gymTb SET status='Unpaid'
WHERE status='Paid' AND nextDateOfPay <= getdate()
You could call this from your application, triggered by manually pressing a button or perhaps using timer logic.
To make it run daily, and independent from your application, you can put the UPDATE statement in a recurring job in SQL Server Agent. For more on that see here:
how to schedule a job for sql query to run daily?
i have a task that i have to filter the records based on DateFrom and DateTo.
in mysql the date fromat is in '2014-07-18 20:03:08' like this.
In front end i used DatetimePicker to textbox..datetimepicker format results gives
'2014/07/09 14:00'.
so not possible for compare db dateformat and datetime formate.
i want datetime picker with seconds..plz help me
A DateTimePicker stores a DateTime in the Value property. You can add desired seconds to it:
DateFrom.Value = DateFrom.Value.AddSeconds(seconds);
datetimepicker format results gives '2014/07/09 14:00'.
Don't use strings as parameters for datetime-columns in MySql. Instead use sql-parameters and pass the DateTime directly:
// add seconds if you want, but i don't see any reason for it
// maybe you want to include the To-date, then you can add a day - one second
DateTo.Value = DateTo.Value.AddDays(1).AddSeconds(-1);
using (MySqlConnection conn = new MySqlConnection("connStr"))
{
try
{
conn.Open();
string sql = #"SELECT t.From, t.To, OtherColumns...
FROM TableName t
WHERE FROM >= #From AND To <= #To";
using(MySqlCommand cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#From", DateFrom.Value);
cmd.Parameters.AddWithValue("#To", DateTo.Value);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// ...
}
}
}
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
DateTime pickers aren't always made for this accuracy.
I suggest using a customized DateTime picker with textboxes to allow your users to input complete time in seconds.
I am trying to insert date in my database table through a textbox. But even if I am converting the string into Datetime I am still getting this error :
"The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value".
I have taken datetime datatype in my database. This is my code :
try
{
SqlCommand cmd = new SqlCommand(#"INSERT INTO tblProject(project_starting_date,project_ending_date)values(#projectstartingdate,#projectendendingdate)", objconn);
//cmd.Parameters.AddWithValue("#projectstartingdate", DateTime.Parse(txtStartingdate.Text).ToString());
//cmd.Parameters.AddWithValue("#projectendendingdate", DateTime.Parse(txtProjectendingdate.Text).ToString());
DateTime stdate;
if(DateTime.TryParse(txtStartingdate.Text, out stdate))
{
//cmd.Parameters.AddWithValue("#projectstartingdate",stdate);
SqlParameter projstrtdate = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projstrtdate.Value = stdate;
cmd.Parameters.Add(projstrtdate);
}
DateTime enddate;
if (DateTime.TryParse(txtProjectendingdate.Text, out enddate))
{
//cmd.Parameters.AddWithValue("#projectendendingdate", enddate);
SqlParameter projenddate = new SqlParameter("#projectendendingdate", SqlDbType.DateTime);
projenddate.Value = enddate;
cmd.Parameters.Add(projenddate);
}
if (objconn.State == ConnectionState.Closed)
{
objconn.Open();
}
norowaffected = cmd.ExecuteNonQuery();
objconn.Close();
}
catch (Exception ex)
{
Response.Write( ex.ToString());
}
Please guide me where I am doing wrong?
Probably your locale configuration is trying to convert the data string in a wrong unexpected format.
Try with the following:
if(DateTime.TryParse(txtStartingdate.Text, out stdate)
{
SqlParameter projectStartingDateParam = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projectStartingDateParam.Value = stdate;
cmd.Parameters.Add(projectStartingDateParam);
}
Do the same with "projectendingdate". Create a SqlParameter with SqlDbType equals to SqlDbType.DateTime and add it to the query command (cmd variable).
If this dosen't work, double check your table structure if it's in DateTime format.
Do a manually insert directly in database via SQL Server Management Studio.
I had the same problem before. I fixed it by deleting the corresponding columns in the data base and recreate it with the correct format "so date time for you". problem was fixed.
it seems there is still information in the data base telling what format it was before.
I have textboxes on a windows form. For some of them there is no date that will initally be saved. The SQL field binded to the text box is of type: date. When I go to save a new record, I get a System.Data.SqlTypes.SqlTypeException:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
How can I save this record, when I don't have a date to put in the date field yet?
This is the code I'm using
public static bool UpdateEngOrd(EngOrd oldEngOrd, EngOrd newEngOrd)
{
SqlConnection cnn = SqlDB.GetConnection();
string strsql =
"UPDATE EngOrd SET " +
"filetype = #newfiletype, reqmeetdue = #newreqmeetdue " +
"WHERE eo = #oldeo";
SqlCommand cmd = new SqlCommand(strsql, cnn);
cmd.Parameters.AddWithValue("#newfiletype", newEngOrd.FileType);
if (newEngOrd.ReqMeetDue == DateTime.MinValue)
cmd.Parameters.AddWithValue("#newreqmeetdue", DBNull.Value);
else
cmd.Parameters.AddWithValue("#newreqmeetdue", newEngOrd.ReqMeetDue);
cmd.Parameters.AddWithValue("#oldeo", oldEngOrd.EO);
try
{
cnn.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
cnn.Close();
}
}
try like this,
Dim _Date As SqlDateTime
_Date = SqlDateTime.Null
If (IsDBNull(Me.txtBox.Value)) Then
_obj.Date= _Date
Else
_obj.Date=Convert.ToDateTime(txtBox.Value)
End If
Have you make this date field in sql table nullable ?
I am not sure, but this can be a problem in your case
You can use the following to make it nullable
ALTER TABLE [TableName] ALTER COLUMN [ColumnName] INTEGER NULL
You're setting it to a new DateTime, which defaults to DateTime.MinValue which is 1/1/0000. Try passing in DBNull instead.
I found the issue. The syntax above works. The problem was in the ADD part of the code (not posted). I thought it was with the update portion
I need to insert a row in my table in oracle from C# (Windows Forms)
conn.Open();
OracleCommand cmd = new OracleCommand("INSERT INTO RECIPES(id,name,time_cooking,time_prep,price,directions,user_name,submit_timestamp) VALUES (:id, :name, :time_cook, :time_prep, :price, :directions, :user_name, :sub_time)",conn);
cmd.Parameters.AddWithValue(":id",x);
cmd.Parameters.AddWithValue(":name",textBox10.Text);
cmd.Parameters.AddWithValue(":time_cook", textBox9.Text);
cmd.Parameters.AddWithValue(":time_prep",textBox8.Text);
cmd.Parameters.AddWithValue(":price", textBox6.Text);
cmd.Parameters.AddWithValue(":directions",richTextBox2.Text);
cmd.Parameters.AddWithValue(":user_name",this.username);
cmd.Parameters.AddWithValue(":sub_time",DateTime.Now.ToString("MM/dd/yyyy"));
try
{
cmd.ExecuteNonQuery();
}
catch (OracleException ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
I get the error below.
ORA-01843: not a valid month
I checked in oracle :
select *
from nls_session_parameters;
and returned NLS_DATE_FORMAT mm/dd/yyyy
You shouldn't pass the date as a string; you should pass it as a date instead... just remove the ToString call:
cmd.Parameters.AddWithValue(":sub_time", DateTime.Now);
If you pass a string, it will be parsed using the format specified by the nls_date_format parameter in the database. If the format you pass is not the one the database expects, the parsing will fail. By passing the date itself, you don't need to worry about the format.