I have in my Ms-Access database table, a date field in Short Date format.
I have in my C# program DateTimePicker control in dd/MM/yyyy short date format
I try to insert data using C# code like this:
SQL = "insert into MyTbl(D_from,D_to) values (#MyFrom,#MyTo)";
OleDbCommand Cmd = Conn.CreateCommand();
OleDbParameter dateparam1 = Cmd.Parameters.AddWithValue("#MyFrom", DbType.DateTime);
dateparam1.Value = dt_From.Value;
OleDbParameter dateparam2 = Cmd.Parameters.AddWithValue("#MyTo", DbType.DateTime);
dateparam2.Value = dt_To.Value;
Cmd.CommandText = SQL;
Cmd.ExecuteNonQuery();
and I got the error: Data type mismatch in criteria expression.
change Parameters.AddWithValue to Parameters.Add
Cmd.Parameters.Add("#MyFrom", DbType.DateTime);
if you use Parameters.AddWithValue then you need to pass the Value as Second Parameter, not the DataType
Cmd.Parameters.AddWithValue("#MyFrom", dt_From.Value);
and also you need to set the CommandType as Text
Take a look at this question
Data type mismatch in criteria expression | Access, OleDb, C#
Try this
dateparam1.Value = dt_From.Value.ToShortDateString();
dateparam2.Value = dt_To.Value.ToShortDateString();
Otherwise have look at this :
Date values must be either delimited according to the ODBC canonical date format or delimited by the datetime delimiter ("#"). Otherwise, Microsoft Access will treat the value as an arithmetic expression and will not raise a warning or error.
For example, the date "March 5, 1996" must be represented as {d '1996-03-05'} or #03/05/1996#; otherwise, if only 03/05/1993 is submitted, Microsoft Access will evaluate this as 3 divided by 5 divided by 1996. This value rounds up to the integer 0, and since the zero day maps to 1899-12-31, this is the date used.
A pipe character (|) cannot be used in a date value, even if enclosed in back quotes.
Related
I want the current day, month and year in inserted in my database.
The format needs to be: YYYY-MM-DD. How to do this? I use de datatype 'date' in my table. It has to be the same value as what it is in the database. I use C#.
Now I get the error: 'Error converting data type nvarchar to date'
Code:
string datenow = DateTime.Now.ToString("yyyy-mm-dd");
I use a Stored Procedure for adding the date value (and some other things):
conn.Open();
SqlCommand cmd = new SqlCommand("spAddContentment", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#question", SqlDbType.VarChar, 220);
cmd.Parameters.AddWithValue("#employeeid", Variabels.employeeid);
cmd.Parameters.AddWithValue("#score", SqlDbType.Char).Value = score;
cmd.Parameters.AddWithValue("#comment", SqlDbType.VarChar).Value = TextBxComment.Text;
cmd.Parameters.AddWithValue("#date", SqlDbType.Date).Value = datenow;
cmd.ExecuteNonQuery();
replace
cmd.Parameters.AddWithValue("#date", SqlDbType.Date).Value = datenow;
with
cmd.Parameters.AddWithValue("#date", SqlDbType.Date).Value = DateTime.Now;
since
Now I get the error: 'Error converting data type nvarchar to date'
says that you've tried to insert a string but the procedure expects a date.
If you want to skip the time part, you can use DateTime.Now.Date or DateTime.Today
The format needs to be: YYYY-MM-DD
Noooooooo!!
A date here should be stored as a typed value - perhaps of type date (no time part) or datetime. Now; here's the thing: a date value has no format. It is essentially just a number. It is simply incorrect to even ask the question "what (text) format is my date stored as", in the same way that it would be incorrect to ask what (text) format an int is stored as. Quite simply: it isn't, because it isn't text.
If you are storing dates (or integers) as text (in some kind of [n][var]char(...) column, for example): that is a problem, and can lead to huge confusions, problems, and inefficiencies - including problems with sorting, filtering, and i18n/l10n problems.
Instead: declare the column as date or datetime, and use a typed value from .NET to populate it, for example passing down a SQL parameter with a value that is a .NET DateTime. The ADO.NET SqlClient layer knows how to connect those things, and all the right magic will happen.
Only when you are actually displaying a date in some way does it become correct to ask about the format. It is, for example, perfectly correct to ask:
I have a DateTime value that I got from the database; what display format should I use in my web-page to display it?
The important point being : it is now a display concern, not a storage concern.
i want to insert data into my tbl_Transaction_Master table.
here is my database table tbl_Transaction_Master
and my query for database insert command is
SqlCommand cmd2 = new SqlCommand("insert into tbl_Transaction_Master(Supplier_ID,Order_Price,Unique_ID,Supplier_Name,He_Is_a,Transaction_Date) values ('" + WebUserID + "','" + Session["Order_Price"] + "','" + Session["WebUserid"] + "','"+User+"','WebCustomer',getdate()); SELECT SCOPE_IDENTITY()", conn);
int temp = cmd2.ExecuteNonQuery();
Session["order_ID"] = temp;
i am getting the error as mentioned above.
There are many problems in your code, not just the one that raises the current exception.
First: You have text fields with a precise size, you cannot insert more characters than the size of the field. We don't know anything about the value passed for the SupplierName but the string WebCustomer is 11 chars and you try to insert it in a field with space only for 10 chars.
Second: Using nchar means that your fields are always filled with spaces to reach the length required. Of course this is inefficient with a lot of records, not to mention the work required to trim away those spaces when you need to show your data.
Third: ExecuteNonQuery returns the number of rows affected by your command. In this case it is always 1, you don't get the return value of SELECT SCOPE_IDENTITY(). Use ExecuteScalar.
Fourth: Some of your fields are numeric, you insert strings for them. This means that the database engine try to convert them back to the correct datatype. Usually, for integers, you can go away freely, but with floats there is a higher chance that you get a datatype mismatch error caused by difference between the locale settings of your code and the locale settings of your database. Fix for that in the next point.
Fifth: You should use parameters not string concatenation. This avoids the Sql Injection hack or the parsing error caused by automatic conversion of a string back to a numeric value. A mismatch from the locale settings used in your code and the database setting will cause errors. With a parameter you specify the type and do not convert the value. The database engine is happy.
So.....(after changing to nvarchar and after checking the length of the values)
string cmdText = #"insert into tbl_Transaction_Master
(Supplier_ID,Order_Price,Unique_ID,
Supplier_Name,He_Is_a,Transaction_Date) values
(#webid, #price,#sessionid,#user,'WebCust.',getdate());
SELECT SCOPE_IDENTITY()";
SqlCommand cmd2 = new SqlCommand(cmdText, conn);
cmd2.Parameters.Add("#webid", SqlDbType.Int).Value = WebUserID
cmd2.Parameters.Add("#price", SqlDbType.Decimal).Value = Session["Order_Price"];
cmd2.Parameters.Add("#sessionid", SqlDbType.Int).Value = Session["WebUserid"];
cmd2.Parameters.Add("#user", SqlDbType.NVarChar).Value =User;
int temp = Convert.ToInt32(cmd2.ExecuteScalar());
Session["order_ID"] = temp;
You are inserting a value in a table column which exceeds column length. That's why the error is there. Check length of each of the values you are inserting into table against respective column lengths.
You are probably inserting a text longer than the designated size. For instance, for Supplier_Name, you are designating an nchar of 20. If you are trying to insert a value larger than 20 characters. You will get this error.
Try changing the size of the data type to fix this.
Two things.
One: The error is occurring because you trying to place data into the field which is larger than allowed so for nchar(20) it will accept an input of 20 or less and pad it up to 20 charters (Varchar will carry the came cap but not pad the data and save space).
Two: It is safer and advised as a best practice to use parameters when inserting values into the database.
You are inserting more characters but you define less.
for example:
column datatype is varchar(5) but you are inserting 6 characters.
I'd like to execute a stored procedure on an sql server 2014. The sql server is set up in German, the user used for connecting to the sql server has also configured German as language. If I try to execute the sql procedure or raw sql, I always get the error
varchar cannot be converted to datetime
even if I provide german datetime values. I've found out that it works if I prepend the sql text with the command SET DATEFORMAT dmy.
The problem is the same for ADO .NET as well as Entity framework. Setting the thread and ui culture to German also didn't help.
It seems that C# SQL Connection sets the culture to default (English) independently of thread culture, date format or sql server language.
Any ideas highly appreciated how to set the culture correctly - such that I don't need to send always SET DATEFORMAT dmy before the real sql text.
UPDATE
This is my code to call the sql stored procedure and pass the dates using the c# sql parameter.
SqlConnection sqlConnection = null;
try
{
// open connection to the database
sqlConnection = new SqlConnection(Convert.ToString(ConfigurationManager.ConnectionStrings[ProductivityAnalyzerDatabase.ConnectionStringName]));
sqlConnection.Open();
// setup command
var sqlCommand = new SqlCommand("UpdateEmployeeBalances", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#employeeId", employeeId));
sqlCommand.Parameters.Add(new SqlParameter("#startDate", startDate));
sqlCommand.Parameters.Add(new SqlParameter("#endDate", endDate));
sqlCommand.ExecuteNonQuery();
}
finally
{
if (sqlConnection != null && sqlConnection.State == ConnectionState.Open)
{
sqlConnection.Close();
}
}
Date values are not stored with their display format.
The problem is that you send your dates to Sql Server as strings, thus forcing sql server to cast the strings to date values. unless you send your dates in ANSI-SQL format (yyyy-mm-dd) this casting might fail or yield unexpected results (is 04/02/2015 April 2nd or February 4th?)
The correct solution, as Steve mentioned in his comment, is to use c#'s DateTime structure as the value of the parameter for the stored procedure. (don't use ToString or anything like that.)
Note that the parameter should be declared as a date type (datetime, datetime2, or date) in the stored procedure itself.
Good day,
You can read more about this issue in this clog:
http://ariely.info/Blog/tabid/83/EntryId/161/Date-displaying-format-vs-Date-storing-format.aspx
in short (from the link above):
Implicit conversion of ambiguous date formats are interpreted according to the language of the connection or the collate of the query. Always keep and following rules, in order to make your work more compatible.
Using .Net you should use a type that is mapped correctly to the SQL Server types. Check this link: https://msdn.microsoft.com/en-us/library/cc716729%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
When you specify dates in DML queries, always use constants way that
are interpreted the same way for all language settings!
for example use format yyyymmdd as 20160227, Use explicit CONVERT statement with an explicit style parameter, Use escape clauses while using ADO, OLE DB, or ODBC.
Remember that those are only display formats. In the database the
data stored in the same way, no matter what is your language!
*datetime is stored as 4 bytes for the date + 4 bytes for the time, Datetime2 is a bit more complex since it is flexible. you can read more on the undocumented internal stored format here.
I hope this is useful :-)
Here's my query:
string sql = #"INSERT INTO MY_TABLE(DATE)
VALUES (convert(datetime, '{0}')";
sql = string.Format(sql, myDate);
myDate is a C# DateTime object and has this value before the string.format:
MY_TABLE has a DATE column as a DateTime type.
I got this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I need to store the myDatevalue in a format like: 31/12/2013 23:59:00 into MY_TABLE.
better to use sql parameters
string sql = #"INSERT INTO MY_TABLE(DATE)
VALUES (#DATE)";
add the parameter to your SqlCommand with SqlParameterCollection.AddWithValue Method
command.Parameters.AddWithValue("#DATE", myDate);
OR, with SqlParameterCollection.Add Method
command.Parameters.Add("#DATE",SqlDbType.DateTime).Value = myDate
DateTime.Now.ToString("dd/MM/yyyy H:mm:ss")
For a list of the parameters see MSDN. (Scroll down a bit to see the table.)
(And it is advised to use Parameters.AddWithValue to avoid SQL injection etc.)
I have val MyDate in my C# program that contain today-date or null.
I have date field in my access 2007 - TdateOpen
I try to insert to the database like this:
SQL = "insert into MyCount(TdateOpen) values ('" + MyDate +"')";
and I get this error:
Data type mismatch in criteria expression
what can be the problem?
Coz in your SQL statement you are entering date as String . Instead of String it should be a date/date format.
Try to surround by # .
You will need to ensure that the date is in US order (mm/dd/yyyy) or ANSI/ISO order, whether you use dash or slash is not important, ANSI/ISO is to be preferred.
Then as, Madhu CM said, the delimiter for dates in Access is hash (#), however, your date can be null and null cannot be delimited, so you will either have to add the delimiter to a date string, if a date is returned, or use two sql statements, one for null and one for date.
You could SQL parameters instead of dynamically embedding the date value into the statement.
SQL = "insert into MyCount(TdateOpen) values (?)";
var parameter = yourCommand.CreateParameter();
parameter.Value = yourDateTime;
yourCommand.Parameters.Add(parameter);
(DISCLAIMER: The code was not compiled nor tested, but it should give you a hint)