In my program i input a record to MS Access database like this
INSERT INTO Stock VALUES('"+ textCode.Text +"', '#"+ datetimepickerDate.Value +"#', somenumber)
With datetimepicker.Value says 09/06/2022 19:35:14
But for some reason when i open MS Access and checked the record, the date magicaly turns 06/09/2022 19:35:14
I didn't change the datetimepicker's format and it should use system date format, and now i can't select or update the record because of the day and the month switches place.
It works without a problem on my PC, but it wont do with my one specific friend's.
How do i fix this?
Thanks~
Here: '#"+ datetimepickerDate.Value +"#' the following happens:
datetimepickerDate.Value returns a DateTime.
That DateTime is used in string concatenation, which causes an implicit conversion to string, using your system date format (09/06/2022, dd/mm/yyyy).
You add a hash in front and in the back (#09/06/2022#). Now it's a string containing an "MS Access date literal".
The problem is that MS Access date literals are always in the format mm/dd/yyyy. Thus, your day and month value may get "switched", depending on the user's system date format.
Solution: Don't use string concatenation for SQLs, use parameterized SQL instead:
How can I add user-supplied input to an SQL statement?
Example:
var sql = "INSERT INTO Stock VALUES (?, ?, ?)";
using (var cmd = new OleDbCommand(sql, myDbConnection))
{
cmd.Parameters.AddWithValue("", textCode.Text);
cmd.Parameters.AddWithValue("", datetimepickerDate.Value);
cmd.Parameters.AddWithValue("", somenumber);
cmd.ExecuteNonQuery();
}
Related
I am trying to change the NLS_DATE_FORMAT of a query and I am struggling to do so.
I have used two approaches
1st
// Use the command to change the format
OracleCommand cmd = new OracleCommand("ALTER SESSION SET NLS_DATE_FORMAT = \'YYYY-MM-DD\'", conn);
cmd.ExecuteNonQuery();
// Then do another command
OracleCommand mainCommand = new OracleCommand("SELECT * FROM dates_table", conn);
OracleDataReader reader = command.ExecuteReader();
while(reader.Read())
{
// Read Data
}
This option's queries both succeed, yet the date format still contains the time (HH:MM:SS)
2nd
// Put both commands in the same sql statement
string sql = "ALTER SESSION SET NLS_DATE_FORMAT = \'YYYY-MM-DD\';";
sql += "SELECT * FROM dates_table";
OracleCommand command = new OracleCommand(sql, conn);
OracleDataReader reader = command.ExecuteReader();
while(reader.Read())
{
// Read Data
}
This option does not succeed and gives me the error ORA-0091 which seems to be the semicolon in the first statement. I have also tried removing the semicolon, yet it produces a ORA-00922 error.
I am a bit stuck as of now, any help would be greatly appreciated. Thanks in advance!
An oracle DATE is a binary data type and does NOT store a format so when you get the date column in a 3rd-party application (i.e. C#) you will only get the binary data representing years, months, days, hours, minutes and seconds and not any format.
The NLS_DATE_FORMAT session parameter is the internal format Oracle will use in the user's session to implicitly cast dates to (and from) strings.
The SQL/Plus and SQL Developer client applications also use the NLS_DATE_FORMAT session parameter to control how the binary date values are displayed to the user but this formatting is done on the client application (and not by the Oracle database).
If you want to format a DATE data type then do the formatting in C#.
If you really want to format it in the database then use TO_CHAR to convert each date column (without a format) to a formatted string.
SELECT TO_CHAR(date_column, 'YYYY-MM-DD') AS formatted_date_column
FROM dates_table
OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = "INSERT into AddLoad(ID_Number,Load_Added,Load_Date) values (#ID_Number, #Load_Added,#Load_Date)";
command3.Parameters.AddWithValue("#ID_Number",UserControl_AddLoadConfirmation.INumberValue);
command3.Parameters.AddWithValue("#Load_Added",addbalance);
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
command3.ExecuteNonQuery();
I tried changing the format of my date column (Load_Date) in ms access database to "Short Date" format, when I view all datas to my Datagrid, it still comes with the hour:minute format.
im not sure with the problem maybe it's this code DateTime.Now.ToString()?
If you are going to persist a date or datetime in your database
the type in your database should be datetime (not varchar!)
You should pass DateTime types to your database directly in the command (not a string equivalent)
You should read back a datetime type when querying from the database (not a string equivalent)
So this line
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
Becomes this
command3.Parameters.Add(New OleDbParameter("#Load_Date", OleDbType.Date) { Value = DateTime.Today });
This also ensures that you are passing the correct type to the command so it knows how it is represented in the schema. You really should not call AddWithValue as this does not pass that information in to the command.
Also keep in mind that when working with Ole (ie. access) parameters are positional and not named. That means the order they appear in in the query has to be the same order they appear in within the parameter collection.
I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format
I am inserting some values into db. In DB field received_date is type of datetime datatype I am using following code for inserting But it is showing some exception, I am unable to figure it out.
Exception:
The conversion of a varchar data type to a datetime data type
resulted in an out-of-range value.
SqlConnection con = new SqlConnection("data source=ATLBLRDP-19\\PRIME;database=arp;uid=sa;pwd=****;");
con.Open();
SqlCommand cmd_r = new SqlCommand();
cmd_r.Connection = con;
cmd_r.CommandType = CommandType.Text;
cmd_r.CommandText = "insert into raw_mails(received_date,sender,receiver,subject,body,has_parsed,has_attachments,created_by,created_on,mail_type) Values(#received_date,#sender,#receiver,#subject,#body,#has_parsed,#has_attachments,'" + DateTime.Now + "','" + DateTime.Now + "',#mail_type)";
cmd_r.Parameters.Add("#received_date", em.DateTimeReceived);
cmd_r.Parameters.Add("#sender", em.From);
cmd_r.Parameters.Add("#receiver", em.Receiver);
cmd_r.Parameters.Add("#subject", em.Subject);
cmd_r.Parameters.Add("#body", em.Body);
cmd_r.Parameters.Add("#has_parsed", 1);
cmd_r.Parameters.Add("#has_attachments", em.HasAttachments);
cmd_r.Parameters.Add("#mail_type", 4);
cmd_r.ExecuteNonQuery();
con.Close();
I checked with every query (parameters.add()) all are working but if I try to insert received_date then only it shows exception . Here em is type of EmailMessage.
And I am using sql server 2012 for DB purpose.
You don't give much to go on, but it is clear that you are setting a date value on your Sql server using a string.
There are definitely two and potentially three places you do this, depending on the type of em.DateTimeReceived. When you build your CommandText you also insert DateTime.Now twice, implicitly calling .ToString() for the conversion.
However, calling .ToString() will use your system's locale. For example, I am in the UK, so today's date (December 13) is written out as "13/12/2013 14:02:08". If I assign this string to a sql datetime it will fail, because my Sql server is using it's default US locale - so it reads 13 as the month and 12 as the day, and throws exactly the error you've seen.
So in order to fix this, you need to either:
output the dates as strings using an explicit format that matches your Sql server's collation (using DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") or similar)
ensure that all of the dates passed in are actual DateTime variables and not strings, allowing the SqlCommand to ensure formatting is correct
The valid range for the datetime data type is 1753-01-01 through 9999-12-31 (Date and Time Data Types and Functions (technet))
If the em.DateTimeReceived property is smaller than 1753-01-01, you will get this error. Depending on data conversion from .NET to SQL, this might also be the case when DateTimeReceived is null.
Ensure that your property value is always greater than 1753-01-01 or use the datetime2 data type which has a range starting at 0001-01-01.
on a side note: Is there a specific reason you are still using the legacy datetime data type? Microsoft recommends "Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications." (msdn)
Either change the DateTime.Now to DateTime.Now.ToString("yyyy/MM/dd HH:mm") or pass them as parameters, similar to your other values.
I have this C# code:
string RegisterDate = DateTime.Now.ToString();
RegisterDate = RegisterDate.Remove(10);
RegisterDate = RegisterDate.Replace('/', '-');
RegisterDate = String.Join("-", RegisterDate.Split('-').Reverse());
Which gives thie result: 01-06-2013
The problem is that when I try to insert it to the table I get this result: 21/06/1894
When I get the date via input it works great in the same date format, so why in this case it doesn't work?
update
If I try this:
var RegisterDate = DateTime.Today.Date;
I get Error :
Syntax error (missing operator) in query expression
Wish for help, thanks!
Don't use a string conversion at all. Assuming your data type in the database is DateTime or something similar, just use a parameter and specify its value as the DateTime in your C# code to start with. (I'm assuming you're already using parameterized SQL rather than embedding data straight in your SQL. If you're not using parameters yet, start right away!)
I'd suggest using DateTime.Today to make it clearer that you're only interested in the date part. (Note that this means that the same code running in different places could end up inserting different dates - is that okay? Normally I don't like letting the system local time zone affect things.)
You should generally avoid string conversions unless you really need a string representation of the data. At other times they just cause trouble.
EDIT: You asked for an example. It would be something like:
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(
"INSERT INTO Foo (Name, RegisterDate) VALUES (#Name, #RegisterDate)",
connection))
{
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar))
.Value = name;
// TODO: Consider whether you really want the *local* date, or some
// fixed time zone such as UTC
command.Parameters.Add(new SqlParameter("#RegisterDate", SqlDbType.DateTime))
.Value = DateTime.Today;
command.ExecuteNonQuery();
}
}
Try
string RegisterDate = DateTime.Now.ToString("M-d-yyyy");
and then store in database.
There is no need to manually convert date to different representation. You can go through this Custom Date and Time Format Strings. But, I agree on Jon Skeet's comment below this answer:
If you want to represent a date/time type, use a date/time type. That
way you're able to take advantage of all kinds of things that the
database can do with date/time values, and you'll never get any
non-date/time values in that field.
Note:
DateTime type uses the Gregorian calendar as their default calendar. So, as pointed out by Jon Skeet, this answer won't work with other calenders(Non-Gregorian calendars).