so here's my code
cmd.CommandText = "insert into tbl_project (`sampleField`) values(#sample)";
cmd.Parameters.AddWithValue("#sample", DateTime.Now.ToString());
This is what's happening.
When I run my solution/project on the Unit that have the database through xampp. I can perfectly put the right date on the database.
But when run the solution/project from a different unit and remotely access the database. The date being saved to my database become 0000, not the correct date. How to fix this. Please help.
BTW. I can perfectly remotely insert strings and numbers on the database. the only problem is the date. its becoming null or 0000.
You shouldn't convert the date to string. If you do, the results depend on the culture settings on the computer where you run the code.
Add the parameter as DateTime:
cmd.Parameters.Add("#sample", SqlDbType.DateTime).Value = DateTime.Now;
It's better to use Parameters.Add instead of AddWithValue because it lets you specify the data type of the parameter explicitly.
Related
I have a program that is moving data between two tables in a database. For this, I am using a SQL query and the System.Data.SqlClient package.
All of a sudden, this query throws an error when executing.
SQLCommand.ExecuteNonQuery is throwing:
Conversion failed when converting date and/or time from character string.
I have isolated the line with the conversion to:
AND DATEDIFF(dd,GETDATE(),SUBSTRING(a.date, 1, 10))<14
where a.date is the datetime as varchar. The query is a INSERT-SELECT query, and if I run only the SELECT part, it works. Even more strange is that this query works perfectly fine to run in SSMS both with and without data found.
Have anyone else seen this case lately?
where a.date is the datetime as varchar.
well there's your main problem. If you are storing a date/time: use the appropriate storage type in the database. You have a wide range to choose from, for example date, smalldatetime, datetime and datetime2 - and: SQL Server will know how to correctly understand and work with that data.
Ultimately the problem here is that SUBSTRING(a.date, 1, 10) isn't giving a result that SQL Server understands as a date through implicit string conversion operations. This approach is a: inefficient, and b: brittle (especially between cultures), hence why you simply shouldn't do that. If you store the data appropriately: all the problems will go away.
However! You could also use CONVERT to tell SQL Server to interpret the string as a date/time, explicitly telling it the format you expect (as a number code), so that it stands a chance.
If your a.date (and substring) isn't in one of the supported formats: abandon all hope.
BTW; DATEDIFF(dd,GETDATE(),SUBSTRING(a.date, 1, 10))<14 is probably more efficiently done by way of calculating the start-date/end-date of your range once and just comparing with a comparison operator. GETDATE() won't change per row, so "14 days from now" won't change per row. This would make your query a lot more efficient, especially when combined with the correct date/time format - it becomes:
a.date <= #end -- or < #end, or > #end, or >= #end
which can use an index.
Interesting! "No changes has been made to the code, and no new data has entered the queried table since then."
So the question why it doesn't work as the same way really have a many choice for you
Your code just don't run into the problem date data before.
Application server have something changed like date region/culture so it affect the application way of seeing date when communicate with DB server
the 2. but from DB server e.g. Infra team upgrade/patch the DB server, the configuration is affect so this has problem with date format , update/patching Db cause the build-in functions too have upgraded behavior too!)
The statement in double-quote is false.
System.Data.SqlClient 's feature when process the query ?
and so on...
I think finding the causes just from this little information is the very difficult task.
From my little search ,you really should go diving into the query and data as the others tried to suggest.
Conversion failed when converting date and/or time from character string while inserting datetime
This happened today and it's the weirdest thing.
I'm using Entity Framework + LINQ to insert DB Values. There is a datetime column and it was working until 2016/04/01.
Today, when i insert some rows and tried to select them with:
Where BulletingDate = Convert(DateTime, '2016-03-01 00:00:00')
This works, but somehow now when i tried to insert values with this:
a.BulletingDate = DateTime.Parse(txtBulletinDate.Text);
entities.Auctions.Add(a);
entities.SaveChanges();
It adds datetime like: 2016-01-04 00:00:00.000
But Bulletin Date Text is: 2016-04-01 00:00:00
I can't seem to figure out.
Please Help.
Date formats are notoriously fragile; it's very easy for queries that you think are running YYYY-MM-DD to suddenly start doing YYYY-DD-MM or similar over something as minor as a different user logging in to the terminal.
Don't rely on dates passed into databases as strings being parsed exactly as you expect. Pass them in as date objects and you'll get much better results.
The datetime type in SQL Server uses fractional seconds. That's the .000 on the end.
If you can, I suggest switching to datetime2 in SQL Server 2008 and up, which has optional fractional seconds. If you don't need to track fractions of a second, then you can use datetime2(0). It plays nicely with C# DateTime.
Bouild your datetime object like this
DateTime x = new DateTime(2016,01,04);//year month day
so you dont have problems when passing it to entity framework
also if your string is in this format "20140104 00:00:00" you should be safe too (at least MSSQL have no problem with that format, not sure if C# is cool too)
I have a problem in SQL and don't know why this is happening. First I show my code:
for (int i = 0; i < dateList.Count;i++ )
{
String connectionQuery = form1.conStringBox.Text;
SqlConnection connection = new SqlConnection(connectionQuery);
SqlCommand sqlComInsert = new SqlCommand(#"INSERT INTO [" + form1.tableName.Text + "] ([" + form1.cusName.Text + "],[" + form1.date.Text + "]) VALUES(#cusName, #date)", connection);
sqlComInsert.Parameters.AddWithValue("cusName", cusName[i]);
sqlComInsert.Parameters.AddWithValue("date",date[i]);
This modified code came from here:
Update database with date format
I try to describe the most important things:
I have a textfile where I read the values from (there are two columns -> cusName and date). I store them in two lists (cusName list = String, date list = DateTime). Now I want to store them in my database. The columntype of the date column is datetime.
Somehow with the above code I get an exception (string or binary data would be truncated). This happens at the date column. In my SQL Server 2008 it get's displayed as (for example) 2013-10-21 00:00:00.000. Since I'm working on a german computer, when I put them in my List they get displayed as: 21.10.2013 00:00:00.
Now why do I have accepted the answer in the other thread? Because when I tried the above code on another computer it worked. When I'm trying this on the computer I'm sitting right now I get the error. I'm working with SQL Server 2008 and Windows 7 on both computers (but I once realized that there are differences with the case sensivity on SQL Server). So I don't know where the error is. Hope someone can help me.
Sample data from a textfile looks like for every row:
Name1;2013-09-27
I would recommend formatting the date strings in YYYYMMDD format before sending them to the SQL server.
I would assume that passing a DateTime-typed field would handle the conversion automatically, but I haven't worked with servers/computers in different regions, so I don't know that for sure. I do know that SQL will handle converting a "YYYYMMDD" string into a Date/DateTime (continue passing the string as a parameter if you go that route).
On the other hand, the error that you mentioned is not commonly associated with DateTime fields (they will usually give you something about a date conversion failure). I would double-check your name column and the lengths of all of your name inputs, just in case. Could also be multi-byte encoding on the strings that makes them take up more room than they appear to? It's hard to say without knowing what the input looks like!
so i have a string "09/15/2014" and in c# it converts it to date:
DateTime from = Convert.ToDateTime(fromdate);
this outputs "9/15/2014" and when I send it over to sql I get this:
select convert(varchar, '9/1/2014 12:00:00 AM', 101)
which doesn't work for me because I need to keep any leading zero's.
help?
If you're worried about the string formats for dates with Sql Server, you're doing it wrong. As a comment to another answer indicates, SQL Server internally stores all dates in a machine-optimized numeric format that is not easily human-readable. It only converts them to a human-understandable format for output in your developer tools.
When sending dates to Sql Server, always use query parameters. In fact, when sending any data, of any type, to Sql Server in an SQL statement, always use query parameters. Anything else will not only result in formatting issues like your problem here, but will also leave you crazy-vulnerable to sql injection attacks. If you find yourself using string manipulation to include data of any type into an SQL string from client code, step away from the keyboard and go ask a real programmer how to do it right. If that sounds insulting, it's because it's so hard to understate the importance of this issue and the need to take it seriously.
When retrieving dates from Sql Server, most of the time you should just select the datetime field. Let client code worry about how to format it. Do you want leading zeros? Great! The Sql Datetime column will at some point be available in C# as a .Net DateTime value, and you can use the DateTime's .ToString() method or other formatting option to convert the value to whatever you want, at the client.
SQL queries use a date and time format which goes like this:
2014-09-15
That's year-month-day. As per the comments below, this may be different depending on the collation you have on your database (see Scott's comment for a more accurate way to describe this and get dates into this format).
DateTime's ToString method has an overload which takes a formatting string. So you can pass the format you want the string to be output to. Try it like this:
string queryDate = from.ToString("yyyy-MM-dd");
And see what you get. Use that on your query.
But if you really want this done right, use parameters. Like:
SqlCommand command = new Command(connection, "SELECT * FROM foo WHERE someDate = #date");
command.Parameters.AddWithValue("#date", from);
// where "from" is your DateTime variable from the code you've shown.
This will save you the trouble of DateTime to String conversions.
I am trying to fetch the record of 3rd june of 2013 from my database which is made in ms access. Dates are stored in the format of dd/MM/yyyy, below is my query
AND (a.Date = #" + date + "#) ) order by e.E_ID asc
But the amazing thing is i have inserted a record on date of 03/06/2013 which is todays date, while it takes it as 6th march 2013, i have corrected my regional settings, still the same issue. Also in my query i am query for matching date i am using dd/MM/yyyy. Is this a bug from microsoft? please help
Dates are stored in the format of dd/MM/yyyy
I suspect they're not. I suspect they're stored in some native date/time format which is doubtless much more efficient than a 10 character string. (I'm assuming you're using an appropriate field type rather than varchar, for example.) It's important to differentiate between the inherent nature of the data and "how it gets displayed when converted to text".
But the amazing thing
I don't see this as amazing. I see it as a perfectly natural result of using string conversions unnecessarily. They almost always bite you in the end. You're not trying to represent a string - you're trying to represent a date. So use that type as far as you possibly can.
You should:
Use parameterized SQL for queries for many reasons - most importantly to avoid SQL injection attacks, but also to avoid unneccessary string conversions of this kind
Specify the parameter value as a DateTime, thus avoiding the string conversion
You haven't specified which provider type you're using - my guess is OleDbConnection etc. Generally if you look at the documentation for the Parameters property of the relevant command class, you'll find an appropriate example. For example, OleDbCommand.Parameters shows a parameterized query on an OleDbConnection. One thing worth noting from the docs:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. [...]
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.