Error when inserting a record into MS Access - c#

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)

Related

Covert C# Datetime to MySql DateTime format

I have been trying to figure out how to add current datetime from c# into mysql column and that attribute/column is also in 'datetime' format. I am writing this code.
if (comboBox1.Text == "Cash On Delivery")
{
MessageBox.Show("Your order has been placed.","",MessageBoxButtons.OK);
string timeString = DateTime.Now.ToString("YYYY-MM-DD HH:MM:SS");
string constring = "datasource=localhost;port=3306;username=root;password=root";
string query = "insert into artgallery.payment_method where payment_method ='" +comboBox1.Text+ "' AND payment_date='" +formatForMySql+ "' AND payment_amount = '" +variables.total_amount+ "' ";
//rest of the code
}
I get this some syntax error related to the timeString Im trying to insert in my 'payment_date' column.
The right answer is to stop building your SQL like that to start with. Use parameterized SQL, then specify the DateTime value as the parameter value - you don't need a string representation at all in your code.
It's not immediately clear which driver you're using (there are two for MySQL, IIRC) but you should look at the Parameters property of whichever command type you're using.
It's really important to use parameterized SQL - not just to avoid conversion issues like this, but also to prevent SQL Injection Attacks. It also makes your code considerably simpler to read, in my view.
put it like this
INSERT INTO table_name( date_column) VALUES (STR_TO_DATE('2014-12-31 00:00:00','%Y-%m-%d %H:%i:%S')
Also, you put M (which mean of month ) in both month, and minute...
please recheck your format again here
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

How to insert date and time in European format into SQL Server from C#?

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.)

How to make a database consult using a date and time variable?

I have the following line code used to retrieve data from database:
DataTable newEquipmentTable = database.Connection.RetrieveData(database.AdapterType, string.Format("SELECT ID FROM Equipment WHERE Name = '{0}' AND CreatedOn = '{1}'", equipment.Name, equipment.CreatedOn.ToString("yyyy-MM-dd HH:mm:ss.fff")));
It returns an error saying "The conversion of varchar data type to a datetime datatype resulted in an out-of-range value"
When I make a direct consult, using the following query it returns the expected result.
SELECT ID FROM Equipment WHERE Name = 'aa' AND CreatedOn = '2012-04-17 19:42:49.650'
What am I doing wrong?
You're passing a String value to select a datetime field. So you need to convert it to a datetime first:
Convert(datetime,'2012-04-17 19:42:49.650', 102)
Apart from that you might be open for SQL-Injection as #Mr47 has mentioned, use SqlParameters.
Please note that SQL's datetime type cannot hold values prior to 1753-01-01.
Just inspect the SQL string with the debugger before it is used to query the database in order to find the problem.
However, the best thing to do is to use a parameterized query (like in this example); otherwise you're vulnerable to SQL Injection.
What is the value of equipment.CreatedOn?
I think problem with the culture setting either in sql-server or your application. It cannot directly covert your date. User culture setting will solve problem.

Problem with inserting date to Ms-Access database

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.

How to insert date in an Oracle relational database using C#

I have Date Var in Oracle, and I try to insert Data from my C# program
sql = "insert into Table(MyDate) values (" + convert.todatetime(txt) + ")";
I get an Error, what can i do ?
cmd.CommandText = "INSERT INTO Table (myDate)VALUES(:dateParam)";
cmd.Parameters.Add(new OracleParameter("dateParam", OracleDbType.Date))
.Value = DateTime.Now;
cmd.ExecuteNonQuery();
Use parameters. It's going to solve your problem and prevent injection.
Oracle expects it to be an actual date value, not just a string that looks like a date. You have to use the TO_DATE() function to explain how your string is formatted, something like this:
INSERT INTO Table (myDate)
VALUES(TO_DATE('2009-03-30 12:30:00', 'YYYY-MM-DD HH:mi:ss'));
Try using DateTime.TryParse(text) or DateTime.Parse(text)
I know this was a poorly asked question, but I saw some poor answers when I had the same question and ran into this. This is how I solved it, and I'll answer using the OP's context:
Parse the date in to a DateTime variable:
DateTime myDate = DateTime.Parse(txt);
Then parameterize your query:
sql = "insert into Table(MyDate) values (:myDate)";
Set up an OracleParameter:
OracleParameter param = new OracleParameter();
param.ParameterName = "myDate";
param.OracleDbType = OracleDbType.Date;
param.Value = myDate;
Assuming you already have an OracleConnection as connection, set up your command and add your parameter:
OracleCommand cmd = new OracleCommand(sql, connection);
cmd.Parameters.Add(param);
Execute:
cmd.ExecuteNonQuery();
Do NOT waste your time on any of the TO_DATE nonsense. This is for when you are adding something using SQL*Plus or Oracle SQL Developer directly, or MAYBE where you want to send in a STRING variable's value (not a DateTime variable) in the EXACT format that TO_DATE expects and that you assign within the TO_DATE construct within your query or a stored procedure (i.e. to_date('2013-05-13 12:13:14', 'YYYY-MM-DD HH24:MI:SS'). Using a DateTime variable and assigning that to an OracleParameter with an OracleDbType of OracleDbType.Date, assuming you have a DATE field in your table and can parse txt into a DateTime variable, however, is best and easiest.
Easiest way possible:
DateTime inputDate = Convert.ToDateTime("01/01/2019"); //<---Input Sample Date in format
string queryParameters = String.Format("SELECT * FROM TABLE WHERE DATE = '{0}')", inputDate.ToString("dd-MMM-yyyy")); //<-- Converts System.DateTime into Oracle DateTime
//Forget looking anywhere else for an answer, copy and paste and reform this very code
//and see the results
Please bind your variables (like ocdecio tells) ! Not only does it prevent sql injection it is also much faster. Especially in a multi concurrency situation. Read for example here: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28844/building_odp.htm#CEGCGDAB .
"Bind variables are placeholders inside a SQL statement. When a database receives a SQL statement, it determines if the statement has already been executed and stored in memory. If the statement does exist in memory, Oracle Database can reuse it and skip the task of parsing and optimizing the statement. Using bind variables makes the statement reusable with different input values. Using bind variables also improves query performance in the database, eliminates the need for special handling of literal quotation marks in the input, and protects against SQL injection attacks."

Categories

Resources