C# DateTime object + stored procedure - c#

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

Related

Getting oracle error when trying to set date using 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.

save time into SQL Database

I have a SQL Database with the following structure:
I have 4 MaskedTextBox for:
(Structure)
DateFrom: 0000.00.00
DateFromTime: 00:00:00
DateTo: 0000.00.00
DateToTime: 00:00:00
.
SqlCommand cmd = new SqlCommand("INSERT INTO TABELLE2 (MessageHeadline, MessageText, SpecifyUser, CreateDate, CreateTime, CreateUser, DateFrom, DateFromTime, DateTo, DateToTime) VALUES (#MessageHeadline, #MessageText, #SpecifyUser, #CreateDate, #CreateTime, #CreateUser, #DateFrom, #DateFromTime, #DateTo, #DateToTime)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MessageHeadline", TB_MSGHeadline.Text);
cmd.Parameters.AddWithValue("#MessageText", TB_MSGText.Text);
cmd.Parameters.AddWithValue("#SpecifyUser", TB_SpecifyUser.Text);
cmd.Parameters.AddWithValue("#CreateDate", CreateDate );
cmd.Parameters.AddWithValue("#CreateTime", CreateTime);
cmd.Parameters.AddWithValue("#CreateUser", CreateUser);
cmd.Parameters.AddWithValue("#DateFrom", MTB_DateFrom.Text);
cmd.Parameters.AddWithValue("#DateFromTime", MTB_DateFromTime.Text);
cmd.Parameters.AddWithValue("#DateTo", MTB_DateTo.Text);
cmd.Parameters.AddWithValue("#DateToTime", MTB_DateToTime.Text);
connection.Open();
cmd.ExecuteNonQuery();
TB_MSGHeadline.Clear();
TB_MSGText.Clear();
TB_SpecifyUser.Clear();
And finally I want to save these values from my MasketTextBox into my database to use them later.
I try to change the Structure and try some SQL Date/Time formation but i get the error:
You're passing the DATE parameters in the incorrect format. You need to pass them as a valid DateTime which your MaskedTextBox values do not appear to be.
For example, #DateFrom is a SQL Date data type. You should pass it a valid parameter such as a DateTime:
cmd.Parameters.AddWithValue("#DateFrom", DateTime.Now);
You may need to parse the MaskedTextBox values correct using DateTime.TryParse
DateTime parsedDate;
bool success = DateTime.TryParse(MaskedInputOne.Text, out parsedDate);
if (success) {
cmd.Parameters.AddWithValue("#DateFrom", parsedDate);
}
In this case we are only adding the parameter if the conversion succeeds.

Datetime Update format error Asp.Net

I have an italian format datetime string like this:
23/03/2012
the sql command of this update is this in the datetime part:
DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
This works on my Sql server(Italian language) but if i make this on my server(English language) gives me this error:
"the conversion of a varchar data type to a datetime data type
resulted in an out-of-range value"
How can I resolve this?
You should always use parameterized queries to prevent sql-injection and localization issues like this.
So i assume that you are passing this datetime as string to the database.
using(var con = new SqlConnection("connection-string"))
using(var cmd = new SqlCommand("UPDATE dbo.TableName SET DateColumn=#DateColumn WHERE PK=#PK", con))
{
DateTime reg_tes = DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.AddWithvalue("#DateColumn", reg_tes);
// other parameters ...
con.Open();
int affected = cmd.executeNonQuery();
}

Date convertion To yyyy-mm-dd

cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
The value in txtStartDate.Text is like 31-07-2012
I need to get it as 2012-07-31.
For processing in storedprocedure.
My code is like :
cmd = new SqlCommand("DownloadtoXLSheet", conn);
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = DateTime.Parse(txtEndDate.Text);
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = DropDownList1.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt1);
help me out
First off, you don't need the date in a particular format for processing in the stored procedure/database. Once a DateTime has been added as a parameter (of type DateTime), the SQL provider will make sure the SQL server can handle the date.
On the other hand, you might need the date in a particular format for DateTime.Parse to work.
Try:
DateTime.ParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture);
But, maybe you should use DateTime.TryParseExact instead, to avoid exceptions?
Use DateTime.ParseExact method instead of DateTime.Parse.
DateTime result=DateTime.ParseExact("31-07-2012", "dd-MM-yyyy",CultureInfo.InvariantCulture);
try with
DateTime dt = ...;
dt.ToString("yyyy-MM-dd");
In the .ToString() method you can specify a format string
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")

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