Getting oracle error when trying to set date using c# - c#

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.

Related

Updating DateTime in access through C#. Data mismatch

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.

C# DateTime object + stored procedure

I'm calling a stored procedure from my code using SqlCommand, some of the parameters are of DateTime type, when calling the procedure from Management Studio I use the following format yyyy-MM-dd for example 2011-01-01, and results are returned accordingly.
In my C# code I'm creating the DateTime object like the following:
DateTime dateFrom = new DateTime(2011,01,01);
and when I run the application the dates are being complete ignored and all the data is being returned. After the debugging accordingly I'm noticing that the format of the DateTime object is being: {01/01/2011 00:00:00} so probably this is causing the issue.
The parameters are being added to SqlCommand like this:
cmd.Parameters.AddWithValue("#DateFrom", SqlDbType.DateTime);
Any idea please?
Copying code:
using (SqlConnection conn = new SqlConnection(connectionString))
{
DateTime dateFrom = new DateTime(2011,01,01);
DateTime dateTo = new DateTime(2011, 01, 31);
SqlCommand cmd = new SqlCommand(strStoredProcName, conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", SqlDbType.DateTime);
cmd.Parameters.AddWithValue("#DateTo", SqlDbType.DateTime);
cmd.Parameters["#DateFrom"].Value = dateFrom;
cmd.Parameters["#DateTo"].Value = dateTo;
}
There should be no format issue from C# to SQL for date time data type.
There may be 2 things causing this issue:
As far I can remember, you not need to add # for the parameter name
cmd.Parameters.AddWithValue("DateFrom", SqlDbType.DateTime);
The overload of AddWithValue is string parameterName and object value. You have passed SqlDbType.DateTime as the value. Pass your DateTime variable instead.
you have two options either choose Add or AddWithValue with following format:
1) cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = dateFrom;
2) cmd.Parameters.AddWithValue("#DateFrom", dateFrom);
If the datetime parameter in stored procedure is type of DateTime, you need not to essentially pass the value as datetime. You can pass simple string value like below:
cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = "23-03-2013";

c# net connector insert into mysql system datetime error

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

Updating datetime in access table

I'm trying to insert a datetime value into a datatable and then use the oledbdataadapter's update(datatable) method to load it into my database.. but i keep getting a "Data type mismatch in criteria expression." error. My access Data types in the table are:
ID Number
Nombre_Proyecto Text
Codigo_Ine_Proy Text
Cliente text
Fecha_Creacion Datetime (short date)
according to access short date is mm/dd/yyy, wich fits with my datetime/toshortdatestring method? i think so at least.
Any help would be appreciated. Here's my code:
Insert OledbCommand fot the data adapter:
sql = "PARAMETERS [#Fecha_Creacion] datetime;INSERT Into [Proyectos] ([ID], [Nombre_Proyecto],[Codigo_Ine_Proy],[Cliente],[Fecha_Creacion]) Values (#ID,#Nombre_Proyecto,#Codigo_Ine_Proy,#Cliente,#Fecha_Creacion)";
Comando = new OleDbCommand(sql, conn);
Comando.Parameters.Add("#Nombre_Proyecto", OleDbType.VarWChar, 500, "Nombre_Proyecto");
Comando.Parameters.Add("#Codigo_Ine_Proy", OleDbType.VarWChar, 500, "Codigo_Ine_Proy");
Comando.Parameters.Add("#Cliente", OleDbType.VarWChar, 500, "Cliente");
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime);
Comando.Parameters.Add("#ID", OleDbType.Integer, 10000, "ID");
Part where i create the datarow on my datatable:
DataRow newRow = Tabla_Proyectos_BD_General.NewRow();
Max_IDs["Proyectos"] += 1;
newRow["ID"] = Max_IDs["Proyectos"];
newRow["Nombre_Proyecto"] = textBox2.Text;
newRow["Codigo_Ine_Proy"] = textBox1.Text;
newRow["Cliente"] = textBox3.Text;
string x = System.DateTime.Now.ToShortDateString();
newRow["Fecha_Creacion"] = x;
Tabla_Proyectos_BD_General.Rows.Add(newRow);
You should just use
newRow["Fecha_Creacion"] = System.DateTime.Now;
What you see from in the Access is the "formatted date". When interacting thru OleDB you need to use the DateTime and not the formatted string.
string x = System.DateTime.Now.ToShortDateString();
It's a string, not a datetime! hence mismatch.
newRow["Fecha_Creacion"] = System.DateTime.Now;
And your parameterised query should just do it for you.
if you want to show the date you put in there in shortdatestring format (whate ever that is on the pc that does the formatting, get it as a datetime and then format as required.
PS if you want to pass a date as a string to a database, use the formats yyyy-MM-dd or yyyyMMdd. Any other than the universal and unambiguous date formats is just a bug waiting to happen, and never do unless you have to.
Tip when outputting dates, converting them into strings in some format is the last operation, when inputing them, converting to a datetime from the string is the first thing you should do.
Edited after comment
Simplest solution is
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime, System.DateTime.Now);

Date conversion from C# to MySql Format

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");

Categories