I am trying to convert a textbox text into a DateTime so that I can insert it into the database table into a datetime column.
Here is my code
bookingfromdate text is "08/07/2015 03:00:00 pm"
DateTime bookingfrom = DateTime.ParseExact(bookingfromdate.Text.ToString(),
"dd/MM/yyyy h:mm:ss tt", new CultureInfo("en-US"),DateTimeStyles.None);
The value of bookingfrom is 08/07/2015 15:00:00 and when I insert it in the database, it is throwing an exception:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.The statement has been terminated.
Please help.
and the Insert query is
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom + "','" + bookingto + "')";
Always try to use parameterized queries to avoid SQL Injection
In your query you are converting date time to string again like #Matt Johnson said don't do that.
If you are doing please specify the format of date you are supplying because sql always expect date format in MM/dd/yyyy , yyyy-MM-dd etc formats if the date you supplying is 25/10/2015 it will fail because 25 is not a valid month
So if you are still stick with your query try below
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom.ToString("dd/MM/yyyy HH:mm:ss") + "','" +
bookingto.ToString("dd/MM/yyyy HH:mm:ss") + "')";
OR
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo)
Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString())
+ ",'" + bookingfrom.ToString("yyyy-MM-dd HH:mm:ss") + "','" +
bookingto.ToString("yyyy-MM-dd HH:mm:ss") + "')";
The error indicates that you're converting the DateTime back to a string when you pass it along to the database. As shown in your insert query, you are passing it inline the SQL query instead of passing it as a parameter.
The simple answer is: don't do that.
Parameterize your inputs. It will help with your dates, and it will prevent SQL Injection attacks.
Your SQL statement should look like this:
string sql = "INSERT INTO Resources_Booking (ResourceID, BookingFrom, BookingTo) VALUES (#ResourceID, #BookingFrom, #BookingTo)";
Then you should add the actual values as parameters when you execute the statement.
var command = new SqlCommand ...etc...
command.CommandText = sql;
command.Parameters.AddWithValue("#ResourceID", theResourceId);
command.Parameters.AddWithValue("#BookingFrom", bookingFrom);
command.Parameters.AddWithValue("#BookingTo", bookingTo);
...
your bookingfrom is DateTime,why you don not use DbParameter?or you can have a try below
string sql = "Insert into ITResources_Booking (ResourceID,BookingFrom,BookingTo) Values (" + Convert.ToInt32(ddControl.SelectedItem.Value.ToString()) + ",'" + bookingfrom.ToString("YYYY-MM-dd HH:mm:ss") + "','" + bookingto + "')";
Related
I don't know why the date and time is not saving on my Access Database. I follow some tutorial but it seems I'm having some problems on my code.
DateTime getdate = DateTime.Now;
String time = getdate.ToString("F");
and when I add
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity,DateTime)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time +"')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
Im stock. please help. thanks guys
The error says that there are problem on the insert into statement
Name of your column is DateTime which is a keyword. You need to change name of column. Also use Parameterized query don't concatenate strings in query.
List of reserved words.
DateTime myDateTime = Convert.ToDateTime(rd2[0].ToString())
values = myDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " , " + rd2[1].ToString()+ " , " + rd2[2].ToString()+ " , " + rd2[3].ToString()+ " , " + rd2[4].ToString()+ " , " + rd2[5].ToString() ;
i am trying to insert date 2016-04-22 12:58:11 in sql server table of datatype datetime but it gives error "Incorrect syntax near 12"
The string you end up with is similar to this:
2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00
Inserting that into a SQL statement is invalid. You need to wrap each date in single quotes so that you have:
'2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00'
Either way this makes your life difficult and makes your code subject to sql injection and insecure. Consider using parameters like this.
string exampleSQL = "SELECT * from mydatetable where dateOne = #date1 and dateTwo = #date2";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#date1", SqlDbType.DateTime).Value = myDateTime;
command.Parameters.Add("#date2", SqlDbType.DateTime).Value = rd2[1];
This way you dont need to worry about formatting. The system automatically will replace the #date1 and #date2 with the values you specified and it will deal with adding the nescessary structure of the SQL without you having to worry about it.
I strongly suggest using "parametrizing your sql queries"...For example, you can check it out here:
http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
Cheers!
I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}
I m trying to save the date to mysql from jquery *DatePicker* from C#
string datetime = txtDate.Text + " " + time;//05/11/2011 5:30 pm
string getSQL1 =
"INSERT into tblconcertdetail
(Address, City, Pincode, Country, Concert_Date)
VALUES ('" + addr + "','" + txtCCity.Text + "','" + txtCpincode.Text + "','" +
ddlCCountry.SelectedItem.Text + "','" + Convert.DateTime(datetime) + "')";
Here getsql1 shows me the date field filled but in database it stores 0000-00-00 00:00 value.
I m not getting why it is so.
I also try convert.ToString(datetime) to.
As mentioned in comments, you have to use parameters for 2 reasons:
Prevent SQL Injections.
Handle data type conversions. In your case, handling the .NET DateTime type to its equivalent value in database.
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.