I am developing an Attendance Monitoring System and I need to compute the time difference between OutTime and InTime. The problem is I can't do it because the InTime value is in the Database, I can't seem to parameterize it. My query works with Access' query mode but not with C#. Here's my code for the time out button.
private void savetimeout()
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = #" UPDATE TimeinTimeout
SET OutTime = #1 AND HoursWorked = ROUND(([OutTime]-[InTime])*24,2)
WHERE EmployeeID = #2 AND InDate = #3";
command.Parameters.Clear();
command.Parameters.AddWithValue("#1", DateTime.Now.ToLongTimeString());
command.Parameters.AddWithValue("#2", textBox1.Text);
command.Parameters.AddWithValue("#3", DateTime.Now.ToShortDateString());
command.ExecuteNonQuery();
MessageBox.Show("Data Saved!");
this.Hide();
Form1 Mm = new Form1();
Mm.ShowDialog();
}
If I understand correctly, you have a field OutTime that you want to set with the current time and, in the same query, you want to calc the difference between the known value inside the field InTime and the current time.
You could use a query like this
command.CommandText = #"UPDATE TimeinTimeout
SET HoursWorked = #1-[InTime],
OutTime = #2
WHERE EmployeeID = #3 AND InDate = #4";
command.Parameters.Add("#1", OleDbType.Date).Value = DateTime.Now;
command.Parameters.Add("#2", OleDbType.Date).Value = DateTime.Now;
// Is this field really a string?
// If not use the appropriate type and convert the textbox.text
command.Parameters.Add("#3", OleDbType.VarWChar).Value = textBox1.Text;
command.Parameters.Add("#4", OleDbType.Date) = DateTime.Today;
command.ExecuteNonQuery();
Notice that to not confuse the database engine you should specify exactly what your parameters are. Using AddWithValue with DateTime field and passing a string creates a problem because your database engine needs to convert these strings back to datetime values and this conversion could produce unexpected problems. Always specify exactly the type of your parameters.
Related
i need to fetch last modified date of item in table(oracle db).
in db format of modified date=04-DEC-20
while displaying in console modified date=04-09-2020
c# code to fetch modified date
string connString =DBUtils.GetDBConnection();
OracleConnection conn = new OracleConnection();
conn.ConnectionString = connString;
string sql = "select LASTMODIFIED , name from v_vname where name in('hector')";
OracleCommand cmd = new OracleCommand();
// Set connection for command.
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime);
}
}
}
In Oracle, you can format a date as a string with to_char():
select to_char(lastmodified, 'dd-mm-yyyy') as last_modified, name
from v_vname
where name = 'hector'
Side note: name in ('hector') is simpler phrased name = 'hector'.
It's elegant when you use .ToString("dd-MM-yyyy") in C#
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0).ToString("dd-MM-yyyy");
Console.WriteLine("modifieddate:" + LASTmTime);
}
DATE data-type values in Oracle are binary values consisting of 7-bytes (which are always century, year-of-century, month, day, hour, minute and second).
What you are seeing when you say the format is DD-MON-RR is the user interface you are using formatting the binary value as something that you, the user, will understand and for SQL/Plus (and SQL Developer and others) this will be based on the NLS_DATE_FORMAT session parameter and the default NLS_DATE_FORMAT value depends on which territory you say you are using when you setup the database.
What you need to do, is the output a string representation of the DATE formatted according to your requirements. You can either do this in SQL and use TO_CHAR to format the string:
SELECT TO_CHAR( LASTMODIFIED, 'DD-MM-YYYY' ) AS last_modified,
name
FROM v_vname
WHERE name = 'hector'
Or could do it in C#:
DateTime LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime.toString("dd-MM-yyyy"));
I am executing a sql query and storing it in a dataset, from there i am sending an email, everything works as expected, except for this time attached to the date 12:00:00 Am, it looks really weird on the email, i know that this occurs because the data type of that column is date and the object it gets attached to stores it as datetime and hence gets reset to midnight but i am querying sql directly and retrieving the value from the datatable but it still has the time attached to it. anyways to fix this issue i tried the below but it wont work:
string conn = ConfigurationManager.ConnectionStrings["WorkOrderConnectionString3"].ToString();
SqlConnection sqlconn = new SqlConnection(conn);
cmd.Connection = sqlconn;
sqlconn.Open();
cmd.CommandType = CommandType.Text;
String getdatasql = "SELECT WorkOrderNum, Requestor, Date, Department, CompletionDate, MachineDescription, MachineLocation," +
"[Type of Work Order], [Work Required], [WorkPerformed / PartsUsed], [Work Completed By :], [Maint. Supv. Approval]," +
" [Work Comp Date], [Supv Approval Date], Status, [Maint. Supv. Approval Date]" +
"FROM Master WHERE ([Type of Work Order] = N'General') AND (WorkOrderNum = #rockbottom) AND Status = 'Complete' ORDER BY WorkOrderNum DESC";
cmd.CommandText = getdatasql;
cmd.Parameters.AddWithValue("#rockbottom", TextBox10.Text);
SqlDataAdapter getdata = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
showdata.Fill(ds1);
string WorkOrderNum = ds1.Tables[0].Rows[0]["WorkOrderNum"].ToString();
string Requestor = ds1.Tables[0].Rows[0]["Requestor"].ToString();
string Date = ds1.Tables[0].Rows[0]["Date"].ToString();
String date = String.Format("{0:MM/d/yyyy}", Date);
cmd.ExecuteNonQuery();
When i did an debug i got this:
In my email it looks like this:
Tried the Solution still getting the time:
Got it Working :)
This is the problem:
string Date = ds1.Tables[0].Rows[0]["Date"].ToString();
Your Date variable is already a string, so trying to format that as if it's a DateTime isn't going to work. You want something like:
DateTime Date = (DateTime) ds1.Tables[0].Rows[0]["Date"];
... although I'd recommend against having a local variable named Date anyway, especially with a variable called date in scope as well...
I am developing an app in VS2010 c# to fetch a single row data from SQLServer and insert it to MySQL.
I have a table with column name Date_Time containing date and time in 24 hrs. format as shown in below image.
Fetching code is as below.
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}
when I print the value of s_added_date it gives me
My question is why it showing like this and how can I get this time in 24 hrs. format.
Please help to resolve it.
Thanks in advance.
I have a table with column name Date_Time containing date and time in 24 hrs. format
No, you have a table with a column type of DateTime. The values don't inherently have any format - they just happen to be displayed one way in your SQL results viewer, which isn't the same way as .NET formats them by default.
It's very important to understand that the data here is just the date and time - not the format.
To format it in a particular way, cast it to DateTime and then use a ToString overload which allows you to specify the format:
DateTime addedDate = (DateTime) sr["s_added_date"];
string addedDateText = addedDate.ToString("dd-MMM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
See the MSDN articles on standard date/time formatting and custom date/time formatting for more information.
However, if the purpose is really just to insert it into MySQL, you shouldn't convert it into a string at all. Just pass the parameter value straight into the appropriate MySQL command as a parameter. Adding string conversions just adds confusion. Wherever possible, keep data in its "natural" type - which in this case is DateTime.
Make following line:
s_added_date = (dr["s_added_date"].ToString());
To
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy HH:mm:ss"));
Your code will be:
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy hh:mm:ss"));
s_added_by = (dr["s_added_by"].ToString());
}
If ypu want it as 11-Nov-2013 10:23:25 format:
s_added_date = (dr["s_added_date"].ToString("dd-MMM-yyyy hh:mm:ss"));
Try this
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, DATE_FORMAT(s_added_date,'%T'), s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}
i am using mysql net connector and i want to insert some data , without datetime it works but
with date time it gives error.
my code is;
da.InsertCommand = new MySqlCommand("INSERT INTO orders( VALUES('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
da.InsertCommand.Parameters.Add("ORDER_DATE", MySqlDbType.DateTime).Value = oRDER_DATEDateTimePicker.Text;
da.InsertCommand.Parameters.Add("DATE_SHIPMENT", MySqlDbType.DateTime).Value = dATE_SHIPMENTDateTimePicker.Text;
da.InsertCommand.Parameters.Add("PRODUCT_ID", MySqlDbType.Int32).Value = pRODUCT_IDTextBox.Text;
da.InsertCommand.Parameters.Add("QUANTITY", MySqlDbType.Decimal).Value = qUANTITYTextBox.Text;
da.InsertCommand.Parameters.Add("CUSTOMER_ID", MySqlDbType.Int32).Value = textiD.Text;
da.InsertCommand.Parameters.Add("INVOICE_FEE", MySqlDbType.VarChar).Value = comboBoxfee.Text;
da.InsertCommand.Parameters.Add("PROD_TYPE", MySqlDbType.VarChar).Value = pROD_TYPETextBox.Text;
da.InsertCommand.Parameters.Add("BRAND", MySqlDbType.VarChar).Value = bRANDTextBox.Text;
da.InsertCommand.Parameters.Add("MODEL", MySqlDbType.VarChar).Value = mODELTextBox.Text;
da.InsertCommand.Parameters.Add("PRICE", MySqlDbType.Decimal).Value = pRICETextBox.Text;
da.InsertCommand.Parameters.Add("VAT", MySqlDbType.Decimal).Value = vATTextBox.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
error is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES('','0007-12-2012 00:00:00 ', '0007-12-2012 00:00:00
i guess my datetime format is not recognizing by mysql,in my winform oRDER_DATEDateTimePicker.Text and dATE_SHIPMENTDateTimePicker.Text is short datetime.
thanks
Instead of adding (as a single example of a wider problem) dATE_SHIPMENTDateTimePicker.Text, use DateTime.Parse (etc) to get the actual value as a DateTime, and add that:
var when = DateTime.Parse(dATE_SHIPMENTDateTimePicker.Text);
da.InsertCommand.Parameters.Add(
"DATE_SHIPMENT", MySqlDbType.DateTime).Value = when;
The same applies to all the parameters; integers, dates, decimals, etc. In fact, simply having database code (commands etc) and UI code (text-boxes) in the same method tells me something is very wrong: ideally, you would have that via a method somewhere that takes typed parameters:
void CreateOrder(int foo, string bar, DateTime baz, decimal blop, ...)
{
...
}
It is the job of the UI to turn the human input into real values that make sense to other layers, such as your data-access code.
So done properly, the UI would handle the parsing, and then call a separate method that knows nothing about the UI to talk to the database.
Another approach is for the UI to build an object with typed members and pass that in:
void CreateOrder(Order order)
{
...
}
Then the UI does:
var order = new Order();
order.Id = /* todo... */
/* ...for each property... */
CreateOrder(order);
MySqlDbType.DateTime wants DateTime as parameter, and not string.
Use DateTime.Parse(oRDER_DATEDateTimePicker.Text) or DateTime.ParseExact(oRDER_DATEDateTimePicker.Text, format) where format is custom format for date that you choose. It can be "yyyy-DD-MM" or whatever else you want or need.
You seem to have a few typos in your query:
da.InsertCommand = new MySqlCommand("INSERT INTO orders( VALUES('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
^^^ ^^
Put a space between VALUES and (, and remove the parenthesis after orders:
da.InsertCommand = new MySqlCommand("INSERT INTO orders VALUES ('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
Second, (as others have mentioned), you are not be using the correct DateTime format. MySQL will accept DateTime.Parse as an input, but it should also accept a string in this format:
yyyy-MM-dd HH:mm:ss
I have a MySQL database, there's a table which have column Time's Type is Nvachar(50) and its values is kind like this "05/09/2012 20:53:40:843" *(Month-date-year hour:mins:second:msecond)*
Now I want to query to get a record have Time after "10/05/2012 01:00:30 PM".
I had code in C# to converted it to "05/10/2012 13:00:30" before making a query.
My Query :
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
But i got no record. So please tell me how can I can make it return record have time after the time above ???
More Info My C# code :
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
var query = "SELECT * FROM " + tableName + " WHERE capTime > '" + date + "' LIMIT 0, 1";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
I'm so so so so so so sorry. I made a mistake the query must be
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
This query is successful return the record i need :)
But soemhow I have mistyped it into
SELECT * FROM ABCDFEGH WHERE capTime > '05-10-2012 13:00:30' LIMIT 0, 1
Sorry again, topic close. But tks for evveryone tried :)
I recommend using the DATETIME datatype instead of NVARCHAR. Store dates in YYYY-MM-DD HH:MM:SS format, which is the native DATETIME format recognized by MySQL.
Also use date literals in the same format.
Two reasons for this recommendation: First, DATETIME takes only 8 bytes, instead of up to 150 bytes which is the potential size of a multibyte 50 character varchar.
Second, the sort order of DATETIME will be the same as the chronological order. So if you create an index on the Time column, your > comparison can benefit from the index. Your query will be much faster as a result.
Use TIMESTAMPDIFF()
Schema
CREATE TABLE ABCDFEGH (`right` varchar(3), `time` datetime);
INSERT INTO ABCDFEGH (`right`, `time`)
VALUES
('Yes', '2012-10-02 13:00:30'),
('No', '2012-10-15 13:00:30');
SQL Code
SELECT * FROM ABCDFEGH
WHERE TIMESTAMPDIFF(MINUTE, time, '2012-10-05 13:00:30') > 0
LIMIT 0, 1
Explanation
TIMESTAMPDIFF() returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
Fiddle: http://www.sqlfiddle.com/#!2/244cc/1 datetime
Fiddle: http://www.sqlfiddle.com/#!2/063b3/1 varchar(50)
PS1: Time may be a reserved word. Please avoid using it. Else use it with backticks (`).
PS2: The format of time is YYYY-MM-DD not the reverse.
First, why did you save the dates as NVARCHAR? If you are still able to change it to DATETIME datatype and all of the records on it, much better.
But if not, you can use STR_TO_DATE.
SELECT *
FROM tableName
WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') >
STR_TO_DATE('05/10/2012 13:00:30', '%c/%d/%Y %H:%i:%s')
See SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE Formats
UPDATE 1
and your query is vulnerable with SQL Injection. To avoid from it
Parameterized your query
code snippet,
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
String query = "SELECT * FROM " + tableName + " WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') > STR_TO_DATE(#dateHere, '%c/%d/%Y %H:%i:%s')";
using (MySqlConnection connection = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
command.Parameters.AddwithValue("#dateHere",date)
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
catch(MySqlException e)
{
// do something here
// don't suppress the error
}
}
}