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.
Related
I have a birthdate column of type Date in sql database
And in my application I use a dateTimePicker to get the birth date
But when i am trying to insert the date taken from the dateTimePicker:
I get an error :
Incorrect syntax near '12'
And when I try to debug the code I find that the value taken from the dateTimePicker is
Date = {3/21/2015 12:00:00 AM}
The CODE:
//cmd is sql command
cmd.CommandText="INSERT INTO person (birthdate) VALUES("+dateTimePicker.Value.Date+")";
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
What you really should do is use parameters to avoid SQL injection attacks - and it also frees you from string formatting dates - also a good thing!
//cmd is sql command
cmd.CommandText = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Also, it's a recommend best practice to put your SqlConnection, SqlCommand and SqlDataReader into using(....) { .... } blocks to ensure proper disposal:
string connectionString = ".......";
string query = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
As mentioned before the best practice is to use parameters, but if you really need to use a TSQL statement from source you should use date in the format: yyyymmdd
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date.ToString("yyyyMMdd")+"')";
Try including quotes:
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date+"')";
I'd recommend using parameters too.
Try this as string format:
cmd.CommandText="INSERT INTO person(birthdate)VALUES('"+dateTimePicker.Value.Date+"')";
dateTimePicker stores values as 1/1/1900 12:00:00 AM so you should use DATETIME if you're trying to store it since DATETIME's format is: YYYY-MM-DD HH:MI:SS.
You can print the dateTimePicker value using
MessageBox.Show(dateTimePicker.Value.ToString());
to see for yourself.
I am trying to insert date in my database table through a textbox. But even if I am converting the string into Datetime I am still getting this error :
"The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value".
I have taken datetime datatype in my database. This is my code :
try
{
SqlCommand cmd = new SqlCommand(#"INSERT INTO tblProject(project_starting_date,project_ending_date)values(#projectstartingdate,#projectendendingdate)", objconn);
//cmd.Parameters.AddWithValue("#projectstartingdate", DateTime.Parse(txtStartingdate.Text).ToString());
//cmd.Parameters.AddWithValue("#projectendendingdate", DateTime.Parse(txtProjectendingdate.Text).ToString());
DateTime stdate;
if(DateTime.TryParse(txtStartingdate.Text, out stdate))
{
//cmd.Parameters.AddWithValue("#projectstartingdate",stdate);
SqlParameter projstrtdate = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projstrtdate.Value = stdate;
cmd.Parameters.Add(projstrtdate);
}
DateTime enddate;
if (DateTime.TryParse(txtProjectendingdate.Text, out enddate))
{
//cmd.Parameters.AddWithValue("#projectendendingdate", enddate);
SqlParameter projenddate = new SqlParameter("#projectendendingdate", SqlDbType.DateTime);
projenddate.Value = enddate;
cmd.Parameters.Add(projenddate);
}
if (objconn.State == ConnectionState.Closed)
{
objconn.Open();
}
norowaffected = cmd.ExecuteNonQuery();
objconn.Close();
}
catch (Exception ex)
{
Response.Write( ex.ToString());
}
Please guide me where I am doing wrong?
Probably your locale configuration is trying to convert the data string in a wrong unexpected format.
Try with the following:
if(DateTime.TryParse(txtStartingdate.Text, out stdate)
{
SqlParameter projectStartingDateParam = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projectStartingDateParam.Value = stdate;
cmd.Parameters.Add(projectStartingDateParam);
}
Do the same with "projectendingdate". Create a SqlParameter with SqlDbType equals to SqlDbType.DateTime and add it to the query command (cmd variable).
If this dosen't work, double check your table structure if it's in DateTime format.
Do a manually insert directly in database via SQL Server Management Studio.
I had the same problem before. I fixed it by deleting the corresponding columns in the data base and recreate it with the correct format "so date time for you". problem was fixed.
it seems there is still information in the data base telling what format it was before.
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();
}
I need to insert a row in my table in oracle from C# (Windows Forms)
conn.Open();
OracleCommand cmd = new OracleCommand("INSERT INTO RECIPES(id,name,time_cooking,time_prep,price,directions,user_name,submit_timestamp) VALUES (:id, :name, :time_cook, :time_prep, :price, :directions, :user_name, :sub_time)",conn);
cmd.Parameters.AddWithValue(":id",x);
cmd.Parameters.AddWithValue(":name",textBox10.Text);
cmd.Parameters.AddWithValue(":time_cook", textBox9.Text);
cmd.Parameters.AddWithValue(":time_prep",textBox8.Text);
cmd.Parameters.AddWithValue(":price", textBox6.Text);
cmd.Parameters.AddWithValue(":directions",richTextBox2.Text);
cmd.Parameters.AddWithValue(":user_name",this.username);
cmd.Parameters.AddWithValue(":sub_time",DateTime.Now.ToString("MM/dd/yyyy"));
try
{
cmd.ExecuteNonQuery();
}
catch (OracleException ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
I get the error below.
ORA-01843: not a valid month
I checked in oracle :
select *
from nls_session_parameters;
and returned NLS_DATE_FORMAT mm/dd/yyyy
You shouldn't pass the date as a string; you should pass it as a date instead... just remove the ToString call:
cmd.Parameters.AddWithValue(":sub_time", DateTime.Now);
If you pass a string, it will be parsed using the format specified by the nls_date_format parameter in the database. If the format you pass is not the one the database expects, the parsing will fail. By passing the date itself, you don't need to worry about the format.
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";