I have 2 controls taking input of the date and time separately. Namely txtDateOutGv for the date and txtNewActionTimeOutGv for the time in hh:mm tt format from a time picker control.
I have tried many ways to insert into my SQL Server 2012 database and have never been able to successfully save the time. The saved time is always 2014-10-04 00:00:00
What is the approach for this? I have tried using stored procedures and it didn't work either.
Dim strActionTimeOut As String = DirectCast(gvActions.FooterRow.FindControl("txtDateOutGv"), TextBox).Text + " " + Convert.ToDateTime(Request.Form(DirectCast(gvActions.FooterRow.FindControl("txtNewActionTimeOutGv"), TextBox).UniqueID)).ToString("HH:mm:ss")
Dim actionTimeOut As DateTime
actionTimeOut = DateTime.ParseExact(strActionTimeOut, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
actionTimeOut = Format(Convert.ToDateTime(strActionTimeOut), "yyyy-MM-dd HH:mm:ss")
insertAction As String = "INSERT INTO Actions([TimeOut]) VALUES ("+ CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut + "', 0), 120)" + ")"
The time format should be as converted in the SQL Server too.. Not sure if that is the issue.
Yes, your code does exactly that:
CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut
You convert the input value to a datetime (unnecessary) and then to a date. The last convert will loose all time info, as expected.
Use a datetime parameter:
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES (#actionTimeOut);");
cmd.Parameters.AddWithValue("#actionTimeOut", actionTimeOut);
cmd.Execute(...);
Seconds will always 00 when using SmallDateTime; seconds supplied will be rounded.
Also, don't use 'HH' for the 'hour' time format, use 'hh'. This will be the same regardless of whether you're using stored procs, direct SQL or a data layer.
Can you try this as a test. Sorry I wrote it in C# but you get the idea; it's just a test to insert a single hard-coded value using the format as shown below. This works for me here - if it doesn't work for you, it's almost certainly the format of your date. Again, note I am not supplying seconds as a parameter because SmallDateTime does not store it: -
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES ('2014-01-01 17:30')", conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
Related
This is in Microsoft SQL Server Management Studio; I have a column Order_Date in my table, and the data type is datetime.
In my ASP.NET web application, I am inserting the date using this query:
"INSERT INTO Order (ORDER_DATE) VALUES ('" + System.DateTime.Now + "')";
I've done the same thing before in another project but didn't get error there. Here I'm getting error when try to insert data. How can I solve this error?
System.DateTime.Now will automatically be converted to a string by C# when it is appended to your INSERT string. However the string it produces will be dependent on the regional/culture settings on the box on which it is executing. It is exceptionally unlikely to produce a datetime string format that SQL understands. So you need to ensure that the correct format is used by explicitly setting it when the string is generated:
"INSERT INTO Order (ORDER_DATE) Values ('" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";
You could just make it a SqlType like:
"INSERT INTO Order (ORDER_DATE) Values ('" + new System.Data.SqlTypes.SqlDateTime(DateTime.Now).ToString() + "');"
Check out:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqltypes.sqldatetime
I want to import date value from excel cell. cell value having "10 October 2013" format. I want to convert it to datetime data type. My code getting error "string was not recognized as a valid datetime"
//code
OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon);
OleDbDataReader olerdr = olecmd.ExecuteReader();
while (olerdr.Read())
{
deldate = olerdr.GetValue(13).ToString();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["irisdb"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("procdamandrugs", con);
cmd.CommandType = CommandType.StoredProcedure;
DateTime dt = DateTime.ParseExact(deldate, "MM/dd/yyyy", CultureInfo.InvariantCulture);//getting error in this line
SqlParameter par9 = new SqlParameter();
par9.ParameterName = "#deleffdate";
par9.SqlDbType = SqlDbType.DateTime;
par9.Value = dt;
cmd.Parameters.Add(par9);
cmd.ExecuteNonQuery();
}
}
Do any one help me to solve this issue.
cell value having "10 October 2013" format.
You are giving wrong format in ParseExact that does not match with the date string you are passing. You need different format than you gave. For day you need dd, for month you need MMMM and for year you need yyyy and you have to give spaces as separator.
It is worth the article Custom Date and Time Format Strings on MSDN for using the string formats for date conversion.
DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);
I recommend the utilizing the DateTime.TryParse method before constructing your SQL objects. Ensure you have quality input before having a conversation with your database.
http://msdn.microsoft.com/en-us/library/ch92fbc1%28v=vs.110%29.aspx
Below is a sample from my own code for an asp.net application
// Validation
DateTime dtOut_StartDate;
if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))
{
Message = "Start date is not a valid format.";
txtStartDate.CssClass = ErrorCssClass.TextBox;
txtStartDate.Focus();
return false;
}
Select Date Time setting from Right lower bottom & Change the format from here......
I have a asp.net project where i have to get input from the user and insert it into date attribute in my database. but instead I have only 0000/00/00. I can't understand why.
the input comes from 3 text boxes. Than i concatenate them and pass it to the query. But something goes wrong. here is the code:
Bday = Month2.Text & "/" & Dates2.Text & "/" & years.Text
Dim StrQwery As String = "INSERT INTO account VALUES(accoint_id, '" & Bday &"')"
Dim smd As MySqlCommand = New MySqlCommand(stquery, myconn)
smd.ExecuteReader()
The same thing happens when I add time to the same string and want to pass it to the dateTime attribute. Can someone tell me what is wrong?
regTime = Month2.Text & "/" & Dates2.Text & "/" & years.Text & CStr(TimeValue(CStr(Now)))
Dim StrQwery As String = "INSERT INTO account VALUES(accoint_id, '" & regTime &"')"
Dim smd As MySqlCommand = New MySqlCommand(stquery, myconn)
smd.ExecuteReader()
MySQL's date-as-string format is yyyy-mm-hh and yyyy-mm-dd hh:mm:ss for datetime. If you insert anything else, like your xxxx/xx/xx, MySQl will not even TRY to guess what format it's in, and simply insert a 0000-00-00 to signal an invalid date.
This is not something you can change. Convert your dates to MySQL's standard format, or deal with the consequences.
I have a problem. I need insert DateTime into SQL from ASP.NET. I have a calendar for inserting date and two DropDownlist. One for hours and other for minutes. I don't know how insert date from calendar and time (hours and minutes) all at once. This code insert only date. For example 28.3.2013 0:00:00.
cmd.CommandText = "insert into Milniky ( datetime ) values ('" + CalendarDz.SelectedDate + DropDownListHz + DropDownListMz +"')";
You should consider creating a DateTime object and parameters while inserting to prevent bad data.
int hour = int.Parse(DropDownListHz.SelectedValue);
int minute = int.Parse(DropDownListMz.SelectedValue);
DateTime dt = CalendarDz.SelectedDate;
dt.AddHours(hour);
dt.AddMinutes(minutes);
cmd.CommandText = "insert into Milniky ( datetime ) values (#dt)";
cmd.Parameters.Add(new SqlParameter("#dt", dt.ToString("yyyy-MM-dd HH:mm:ss")));
You may also want to use DateTime.TryParse(s) to give a better user experience
However in your specific command, I suspect you need to add a space and a colon to the statement to concatenate a date.
Currently your command looks like it's creating something like 2013-3-28130 and what you want is something like 2013-3-28 1:30.
cmd.CommandText = "insert into Milniky ( datetime ) values ('" + CalendarDz.SelectedDate.ToString("MM/dd/yyyy") + " " + DropDownListHz + ":" + DropDownListMz +"')";
I have a textbox and a button on a form.
I wish to run a query (in Vb.Net) that will produce a query with the IN Values.
Below is an example of my code
myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close()
MsgBox("Done!", _
MsgBoxStyle.Information, "Done")
When I enter a single value it works but when I enter values with commas it throws an error:
"Conversion failed when converting the varchar value '1234,4567' to
data type int."
Could someone please help me to solve this or if there is an alternative way?
Many Thanks
Try removing the single-quotes you're wrapping the IN values in:
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 WHERE RecID IN (" & txtRecID.Text & ") ", myConnection)
If you were testing a STRING variable for multiple values, then those multiple values would need to be in quotes.
The reason your first attempt 'almost' worked was because you could also have generated your SqlCommand with each individual value in quotes.
I.E.
UPDATE dbo.Recordings SET Status = 0 where RecID IN ('1234', '5678')
In that case, T-SQL would have done an implicit conversion of each of the string values to INT,
which is what it was attempting to do when you gave it '1234, 5678' but that isn't decipherable as an INT.