truncated datetime Exception in SQL - c#

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!

Related

How to get datetime format of SQL column in C#?

I want to get format of a datetime column to be able to use it in C#. I want to get it and change my variable to this format. I could not find any solution. How to get it? I just want to be able to get the format of existing column and use it as string in C#.
DateTime values in SQL Server are stored as binary values that are not human readable. They are not strings at all.
For C#, you should use the normal .Net primitive DateTime type to talk to the database; NEVER use any string formats; reserve the string for when you output to the user. The ADO.Net library (which also sits underneath other tools like Entity Framework) will efficiently and safely handle transport between your application and SQL Server.
I am building an sql query to search a string value as parameter that comes from frontend.
Great, we can do that. The way we do it to to parse the string to a C# DateTime, and then use the C# DateTime value for the query.
Let me elaborate. I'm worried you're wanting to do something like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= '" + TextBox1.Text "'";
var cmd = new SqlCommand(SQL, connection);
THAT IS NOT OKAY!
It is NEVER okay to use string concatenation to include user data like that. Instead, you must use parameterized queries. And when you do this, one of the things you can do is provide datetime values.
So instead, the code should look more like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= #MinDate";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#MinDate", SqlDbType.DateTime).Value = DateTime.Parse(TextBox1.Text);
But even this is still a little rough, because users will do all kinds of things when entering a date into a raw textbox. You'll be much better off if you can also provide a datepicker that ensures you get a clean input from the user.
All that said, the SQL language does have specific formats for Datetime literal values. You can pick any of these formats and the database will handle it correctly:
yyyyMMdd HH:mm:ss[.fff]
yyyy-MM-ddTHH:mm:ss[.fff]
yyyyMMdd
Note the above formats are very specific and must be followed exactly, but if you do any of these can be cleanly converted to SQL Server datetime values. But again: this is not how the values are stored internally, the need for this should be relatively rare, and it's definitely NOT something you would EVER do for user input.

Convert a datetime() record to date in c# for importation into VFP database

I'm currently building a data export/import tool for pulling data into a Visual Fox Pro database from an excel or CSV document.
I believe the code to be functional, however upon execution I recieve a data type mismatch error.
After some investigation I've notice a difference between the format of the dates I'm pulling and the field I'm pushing to.
The Fox pro database is set up to take Date records, however the data i'm trying to push is in date time format (the original record is date) but as far as I'm aware c# can only natively do datetime conversion.
The code getting the date from excel is as such:
importCommand.Parameters["TENSDATE"].Value = exportReader.IsDBNull(0)
? (object) DBNull.Value
: DateTime.Parse(exportReader.GetValue(0).ToString());
Now, I've seen a lot of people use something like:
exportReader.GetValue(0).ToString("dd/MM/yyyy")
However I can't seem to get this functioning. Can someone advise me on the best way to achieve my goal.
You need to supply the type of the field when adding it to parameters. In this specific case, OdbcType.DateTime for a date field.
importCommand.Parameters.Add("#TENSDATE", OdbcType.DateTime).Value = exportReader.IsDBNull(0)
? (object) DBNull.Value
: DateTime.Parse(exportReader.GetValue(0).ToString());
If you want to parse dates which are in specific format you should use DateTime.TryParseExact method. You'll be able to pass specific format as an argument. Please refer to: https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
(Joshua Cameron-Macintosh, please close your open threads)
Despite my prior warnings, you are trying to do that the hard way, be it. VFP is a good data centric language and is clever enough to put a DateTime value into a Date or DateTime field. It is also clever enough to parse text values that denote a Date(time) - in the case of text, just like any other database or non-database parsers it does the parsing with given rules (such as using common canonical ODBC format of yyyyMMdd HH:mm:ss with no problem, or if instructed to use a format of say DMY, it knows 1/2/2000 means Feb 1st,2000 etc.). In summary here the problem is not on VFP side at all. If you use CSV, then be sure you are using ODBC canonical format for dates (same goes on with SQL Server for example). In case of Excel file, provided you have the correct data types, you can directly transfer with no additional work, particularly that DBNull trial was totally unnecessary, VFP knows DbNull.Value already.
Anyway code always talks better.
For this sample assume you have an excel file (d:\temp\ExcelImportData.xlsx) with SampleSheet sheet where you have the data columns as:
Customer ID: string
Order ID: integer
Ordered On: DateTime && where time parts were insignificant fro demo purposes
Shipped On: DateTime && Has NULL values
(You can build such a sample sheet using Northwind sample database's Orders table)
There is a VFP table (d:\temp\SampleImport.dbf) as the receiver where column information is:
CustomerId: Char(10) NOT NULL
OrderID: Int NOT NULL
OrderDate: Date NOT NULL
ShippedOn: DateTime NULL
Here is the simple read/write using a reader:
void Main()
{
var vfpConnection = #"Provider=VFPOLEDB;Data Source=D:\temp";
var xlsFileName = #"D:\temp\ExcelImportData.xlsx";
var xlsConnection = $#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={xlsFileName};" +
"Extended Properties=\"Excel 12.0;HDR=Yes\"";
var xlsTableName = "SampleSheet$";
using (var xlsCon = new OleDbConnection(xlsConnection))
using (var vfpCon = new OleDbConnection(vfpConnection))
{
var cmdInsert = new OleDbCommand(#"insert into SampleImport
(CustomerId, OrderId, OrderDate, ShippedOn)
values
(?,?,?,?)", vfpCon);
cmdInsert.Parameters.Add("customerId", OleDbType.WChar);
cmdInsert.Parameters.Add("orderId", OleDbType.Integer);
cmdInsert.Parameters.Add("orderDate", OleDbType.Date);
cmdInsert.Parameters.Add("shippedOn", OleDbType.Date);
var readXl = new OleDbCommand($"select * from [{xlsTableName}]", xlsCon);
xlsCon.Open();
vfpCon.Open();
var xlReader = readXl.ExecuteReader();
while (xlReader.Read())
{
cmdInsert.Parameters["customerId"].Value = xlReader["Customer ID"];
cmdInsert.Parameters["orderId" ].Value = xlReader["Order ID"];
cmdInsert.Parameters["orderDate" ].Value = xlReader["Ordered On"];
cmdInsert.Parameters["shippedOn" ].Value = xlReader["Shipped On"];
cmdInsert.ExecuteNonQuery();
}
xlsCon.Close();
vfpCon.Close();
}
}

Date inserted to database become 0000

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.

issue with date between c# and sql converting

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.

using c# datetime in mysql update query

I'm trying to run a query from C# to MySQL (version 5.5.27) using the mysql connector for .net from the MySQL website.
The ultimate goal of the .dll I'm developing is to keep track of the rows that I've read.
The query I use to read the database is:
string strSQL = "SELECT date,ask,bid,volume FROM gbpjpy where `read` = 0";
To read in the date, I have:
DateTime dateTime = mysqlReader.GetDateTime(0);
That works fine.
The table has 5 columns, the last column is called "read". Right after the select query and parsing is done, I execute the following query:
string sqlFormattedDate = dateTime.ToString("yyyy/MM/dd HH:mm:ss");
string query = "UPDATE gbpjpy SET `read` = 1 WHERE `date` = " + sqlFormattedDate;
However, when I check my log, I have the following error:
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 '01:20:08' at line 1.
The first date read in is 2012/08/30 01:20:08 (that's how it appears in the MySQL table, so that's where it gets the 01:20:08).
I've tried var sqlFormattedDate, changing the ToString overload to yyyy-MM-dd (using dashes and not forward slashes) and dateTime.ToString() all to no avail.
Why is MySQL not picking up the entire string?
Basically you should avoid including values in your query directly.
No doubt you could put quotes around the value... but you shouldn't. Instead, you should use paramterized SQL, and put the value in the parameter. That way you don't an error-prone string conversion, you avoid SQL injection attacks (for string parameters), and you separate code from data.
(As an example of how subtly-broken this can be, your current code will use the "current culture"'s date and time separators - which may not be / and :. You could fix this by specifying CultureInfo.InvariantCulture... but it's best not to do the conversion at all.)
Look for documentation of a Parameters property on whatever Command type you're using (e.g. MySqlCommand.Parameters) which will hopefully give you examples. There may even be a tutorial section in the documentation for parameterized SQL. For example, this page may be what you're after.
I suppose you have to put the whole value for the date in quotes. If you actually concatenate your query, it would look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = yyyy/MM/dd HH:mm:ss
That equal sign will only take the value until the first space.
Instead, it should look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = 'yyyy/MM/dd HH:mm:ss'
This is the particular reason in this case, however, concatenating queries like this leads to a real possibility of SQL injection. As a rule of thumb, you shouldn't do it. You can use parameterized queries and there's probably an API of the .NET connector you are using to do that.
Putting the info in a parameter allows the code to format as it needs. Likely, your original issue may have stemmed from using slashes instead of dashes in your date format. I would assume that slashes can work, but most all of the documentation I've seen has dashes separating dates with MySqlDateTimes.

Categories