i am using mysql net connector and i want to insert some data , without datetime it works but
with date time it gives error.
my code is;
da.InsertCommand = new MySqlCommand("INSERT INTO orders( VALUES('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
da.InsertCommand.Parameters.Add("ORDER_DATE", MySqlDbType.DateTime).Value = oRDER_DATEDateTimePicker.Text;
da.InsertCommand.Parameters.Add("DATE_SHIPMENT", MySqlDbType.DateTime).Value = dATE_SHIPMENTDateTimePicker.Text;
da.InsertCommand.Parameters.Add("PRODUCT_ID", MySqlDbType.Int32).Value = pRODUCT_IDTextBox.Text;
da.InsertCommand.Parameters.Add("QUANTITY", MySqlDbType.Decimal).Value = qUANTITYTextBox.Text;
da.InsertCommand.Parameters.Add("CUSTOMER_ID", MySqlDbType.Int32).Value = textiD.Text;
da.InsertCommand.Parameters.Add("INVOICE_FEE", MySqlDbType.VarChar).Value = comboBoxfee.Text;
da.InsertCommand.Parameters.Add("PROD_TYPE", MySqlDbType.VarChar).Value = pROD_TYPETextBox.Text;
da.InsertCommand.Parameters.Add("BRAND", MySqlDbType.VarChar).Value = bRANDTextBox.Text;
da.InsertCommand.Parameters.Add("MODEL", MySqlDbType.VarChar).Value = mODELTextBox.Text;
da.InsertCommand.Parameters.Add("PRICE", MySqlDbType.Decimal).Value = pRICETextBox.Text;
da.InsertCommand.Parameters.Add("VAT", MySqlDbType.Decimal).Value = vATTextBox.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
error is:
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 'VALUES('','0007-12-2012 00:00:00 ', '0007-12-2012 00:00:00
i guess my datetime format is not recognizing by mysql,in my winform oRDER_DATEDateTimePicker.Text and dATE_SHIPMENTDateTimePicker.Text is short datetime.
thanks
Instead of adding (as a single example of a wider problem) dATE_SHIPMENTDateTimePicker.Text, use DateTime.Parse (etc) to get the actual value as a DateTime, and add that:
var when = DateTime.Parse(dATE_SHIPMENTDateTimePicker.Text);
da.InsertCommand.Parameters.Add(
"DATE_SHIPMENT", MySqlDbType.DateTime).Value = when;
The same applies to all the parameters; integers, dates, decimals, etc. In fact, simply having database code (commands etc) and UI code (text-boxes) in the same method tells me something is very wrong: ideally, you would have that via a method somewhere that takes typed parameters:
void CreateOrder(int foo, string bar, DateTime baz, decimal blop, ...)
{
...
}
It is the job of the UI to turn the human input into real values that make sense to other layers, such as your data-access code.
So done properly, the UI would handle the parsing, and then call a separate method that knows nothing about the UI to talk to the database.
Another approach is for the UI to build an object with typed members and pass that in:
void CreateOrder(Order order)
{
...
}
Then the UI does:
var order = new Order();
order.Id = /* todo... */
/* ...for each property... */
CreateOrder(order);
MySqlDbType.DateTime wants DateTime as parameter, and not string.
Use DateTime.Parse(oRDER_DATEDateTimePicker.Text) or DateTime.ParseExact(oRDER_DATEDateTimePicker.Text, format) where format is custom format for date that you choose. It can be "yyyy-DD-MM" or whatever else you want or need.
You seem to have a few typos in your query:
da.InsertCommand = new MySqlCommand("INSERT INTO orders( VALUES('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
^^^ ^^
Put a space between VALUES and (, and remove the parenthesis after orders:
da.InsertCommand = new MySqlCommand("INSERT INTO orders VALUES ('',#ORDER_DATE, #DATE_SHIPMENT, #PRODUCT_ID, #QUANTITY, #CUSTOMER_ID, #INVOICE_FEE, #PROD_TYPE, #BRAND, #MODEL, #PRICE, #VAT)", cs);
Second, (as others have mentioned), you are not be using the correct DateTime format. MySQL will accept DateTime.Parse as an input, but it should also accept a string in this format:
yyyy-MM-dd HH:mm:ss
Related
Have been looking for the answer to this all morning but not found anything that works for me. am using this code to try to change a date value in oracle database, but keep getting the oracle error 'ORA-1843: not a valid month':
using Oracle.DataAccess.Client;
OracleConnection closeDate = new OracleConnection(oradb);
OracleParameter[] prm = new OracleParameter[2];
closeDate.Open();
OracleCommand cmd = new OracleCommand();
prm[0] = cmd.Parameters.Add("paramDate",
OracleDbType.Date, "05/02/2015", ParameterDirection.Input);
prm[1] = cmd.Parameters.Add("paramCRN", OracleDbType.Varchar2, "16118009",
ParameterDirection.Input);
cmd.Connection = closeDate;
cmd.CommandText = "update vec_complaint set CLOSURE_DATE = :1 where ID = :2";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
closeDate.Close();
closeDate.Dispose();
I'm guessing that I need to state the date format of DD/MM/YYYY somehow but can't figure out how.
Dates have no format, they are binary values, just like as decimals, doubles, floats. Formats have meaning only when they are rendered to strings or parsed from strings.
Assuming that CLOSURE_DATE is a date-typed column, not a (n)varchar field, you only have to pass the DateTime object as a parameter value:
var myDate=new DateTime(2015,09,29);
prm[0] = cmd.Parameters.Add("paramDate", OracleDbType.Date, myDate,
ParameterDirection.Input);
In fact, it's good practice to always pass DateTime objects around instead of date or time strings. Text should be parsed to DateTime or TimeSpan immediately upon input, when you know what the text format and/or user locale is. Trying to determine the format 2 layers down, especially in web applications, is neither easy nor safe.
In your case, you could use a DatePicker or Calendar control on the input form to retrieve the closure date as a DateTime object, then pass this to the data access code.
I have a date and time loaded into a textbox for editing, but I need to store it as a datetime in my access database not a string and cannot remember or find the syntax to parse it in my SQL parameters... here is my code anyway...
string strSql = "UPDATE OCR SET OCR = #OCR, [OCR Title] = #OCRTitle, DeadlineDate = #DeadlineDate;";
using (OleDbConnection newConn = new OleDbConnection(strProvider))
{
using (OleDbCommand dbCmd = new OleDbCommand(strSql, newConn))
{
dbCmd.CommandType = CommandType.Text;
dbCmd.Parameters.AddWithValue("#OCRTitle", textBox6.Text);
dbCmd.Parameters.AddWithValue("#OCR", textBox5.Text);
dbCmd.Parameters.AddWithValue("#DeadlineDate", textBox7.Text);
newConn.Open();
dbCmd.ExecuteNonQuery();
}
}
You're specifying a string as the deadline date value. You should specify a DateTime instead.
You can use DateTime.Parse (or DateTime.ParseExact, or DateTime.TryParseExact) to parse the text representation if you really have to - but it would be better to use a date-based control to start with, rather than having a text representation at all.
(It's not clear what sort of application this is - WinForms, ASP.NET etc - but most GUIs have some sort of date picker these days.)
EDIT: Additionally, you need to change the order in which you add the parameters to the command such that it matches the order in which the parameters are used in the SQL statement. These are effectively positional parameters - the names are ignored. It would probably be clearer to use ? than named parameters in the SQL.
I have a simple SqlCommand in which I want to return all records within a specified DateTime range. (both Date and Time are involved)
var dataReader = new SqlCommand(
#"Select RecordID from RecordTable
where RecordTable.WorkingDT between '"+ _startDt +"' and '"+ _endDt +"'",
_sqlConnection).ExecuteReader();
how do I have to set the values for _startDt and _endDt?
You can try this:
var dataReader = new SqlCommand(
#"Select RecordID from RecordTable
where RecordTable.WorkingDT between '"+ _startDt.ToString("yyyy-MM-dd HH:mm:ss") +"' and '"+ _endDt.ToString("yyyy-MM-dd HH:mm:ss") +"'",
_sqlConnection).ExecuteReader();
Where _startDt and _endDt are type of DateTime.
If you add them as proper parameters in your command, you don't need to worry about formatting. The added benefit of getting into the habit of using these is that you don't have to worry about SQL injection when you were to supply strings as parameters.
Have a look at http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
It shows how to use parameters in your queries. I don't think it needs to be spelled out completely.
An example (copy/pasted from the site):
// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = #City", conn);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#City";
param.Value = inputCity;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
// get data stream
reader = cmd.ExecuteReader();
And yes, defining the parameters can be done shorter that 3 lines per parameter. But that's left up to the reader.
#kmatyaszek, While commonly used, the "yyyy-mm-dd HH:mm:ss" date format is not guaranteed to be unambiguously parsed by SQL server. If you must create SQL from concatenating strings (not necessary in this case as René has shown) then you should use the ISO8601 format, which is just the same but with a T in the middle: "yyyy-mm-ddTHH:mm:ss".
http://msdn.microsoft.com/en-us/library/ms190977%28v=sql.90%29.aspx
"The advantage in using the ISO 8601 format is that it is an
international standard. Also, datetime values that are specified by
using this format are unambiguous. Also, this format is not affected
by the SET DATEFORMAT or SET LANGUAGE settings."
For a demonstration why, try this rerunnable Sql script.
if object_id('tempdb..#Foo') is not null drop table #Foo;
create table #Foo(id int, d datetime)
-- Intend dates to be 12th Jan.
set dateformat ymd
insert into #Foo(id, d) values (1, '2012-01-12 01:23:45') -- ok
insert into #Foo(id, d) values (2, '2012-01-12T01:23:45') -- ok
set dateformat ydm
insert into #Foo(id, d) values (3, '2012-01-12 01:23:45') -- wrong!
insert into #Foo(id, d) values (4, '2012-01-12T01:23:45') -- ok
select * from #Foo order by id
if object_id('tempdb..#Foo') is not null drop table #Foo;
How to convert C# datetime to MySql Datetime format. I am getting value from text box like 7/27/2011 this format. But i want to convert in this format 2011-7-27. So here i am stuking. Please help me. My objective is to filter the record between two dates and show in a listview control in asp.net.
Here is my code:
DateTime dt1 = Convert.ToDateTime(txtToDate.Text);
DateTime dt2 = Convert.ToDateTime(txtFromDate.Text);
lvAlert.DataSource = facade.GetAlertsByDate(dt1, dt2);
lvAlert.DataBind();
I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.
EDITED TO ADD SAMPLE CODE
This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.
public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Alerts WHERE EventTime BETWEEN #start AND #end", conn);
DataTable table = new DataTable();
try
{
SqlParameter param;
param = new SqlParameter("#start", SqlDbType.DateTime);
param.Value = start;
cmd.Parameters.Add(param);
param = new SqlParameter("#end", SqlDbType.DateTime);
param.Value = end;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return table;
}
This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "#" in parameter names. The technique for MySQL should also be very similar.
For many databases, shortcuts may exist for creating parameters, such as:
cmd.Parameters.AddWithValue("#start", start);
This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.
Hope this helps.
You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :
the format for 2011-7-27 is yyyy-m-dd
Assuming you are doing this in the database I think you should use date_format to get in the required format
Something like date_format(dateval,'%Y-%c-%d') (Not tested)
I use:
string fieldate = dt1.ToString("yyyy-MM-dd");
I'm trying to insert a System.DateTime into an Access database using a parameterized OleDbCommand in C#. However, it throws a Data type mismatch in criteria expression exception.
Here is my code:
string statement = "INSERT INTO Log (SCTID, LogDateTime, Type, Message, Visible)" +
"VALUES (?, ?, ?, ?, ?);";
OleDbCommand insertCommand = new OleDbCommand(statement, connection);
// Add parameters to the command
insertCommand.Parameters.AddWithValue("#SCTID", OleDbType.Integer).Value = SCTID;
insertCommand.Parameters.AddWithValue("#LogDateTime", OleDbType.DBTime).Value = dateTime;
insertCommand.Parameters.AddWithValue("#Type", OleDbType.Integer).Value = (int)logType;
insertCommand.Parameters.AddWithValue("#Message", OleDbType.BSTR).Value = message;
insertCommand.Parameters.AddWithValue("#Visible", OleDbType.Boolean).Value = visible;
insertCommand.ExecuteNonQuery();
When I comment out the LogDateTime line, the rest of it works. My problem is that no matter what I use for the DateTime type, it doesn't work. I've tried:
OleDbType.Date, OleDbType.DBDate, OleDBType.DBTimeStamp, DbType.Date, DbType.DateTime, DbType.DateTime2
I've also tried:
insertCommand.Parameters.AddWithValue("#LogDateTime", dateTime);
It doesn't work either. Nothing I've read through Google or SO works. Also, note that I do need both date and time, not just a date alone.
insertCommand.Parameters.AddWithValue("#SCTID", OleDbType.Integer).Value = SCTID;
...
That's a very strange way to use AddWithValue. Its second parameter is not the type - it's the value that you want it to have. As given, you just end up using the integral value of enumeration member OleDbType.Integer, and then immediately overwrite it by assigning to Value property. It should be either:
insertCommand.Parameters.AddWithValue("#SCTID", SCTID);
or:
insertCommand.Parameters.Add("#SCTID", OleDbType.Integer).Value = SCTID;
Regarding the statement itself - why do you use ? for placeholders in command text, but then use names when adding parameters to the collection?
Regarding the actual problem - looks like it's a known bug, and the workaround is to truncate milliseconds in your DateTime value before assigning, and to use OleDbType.Date.