Insert datetime from asp.net to sql server - asp.net

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

Related

Conversion of varchar into datetime data type

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

Unable to correctly save DateTime into SQL Server 2012

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

View SQL entries that were entered within past 24 hours

I am trying to view the entries into my sql database that were entered within the last 24 hours. My database has a Date and Time field that are set when the record is entered. I am currently using the following code but it is not working. The is code executed correctly so I suspect that my SQL query is incorrect.
DateTime Time = DateTime.Now;
Time = Time.Subtract(new TimeSpan(24, 0, 0)); //Get DateTime of 24 Hours Ago
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable WHERE Date>'" + Time.ToShortDateString() + "' AND Time>'" + Time.ToShortTimeString() + "'";
My Table name is correct and the field names are correct.
Thanks
You need to delimit your field names since they are reserved keywords:
SqlDataSource1.SelectCommand =
"SELECT * FROM DataTable WHERE [Date]>'" + Time.ToShortDateString() + "' AND [Time]>'" + Time.ToShortTimeString() + "'"
This is a very good reason to choose field names that are not reserved words in SQL.
If these are both one field, then you can just do a single evaluation of Date and Time:
WHERE <datetime field name> > GetDate() - 1
SELECT * FROM DataTable WHERE [DATE] > getdate() - 1

why this code enter two entries into the database

i have a code that retrieve some content and enter it the database :
MySqlConnection conn = new MySqlConnection(#"connection string");
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "')", conn);
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO copy (cv) VALUES ('" + mainEditor.Content.Replace("'", "''") + "')",conn);
conn.Open();
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
conn.Close();
it connects and enters the data fine but it enters the data in two not one (it creates two rows instead of one)
i am using asp.net 3.5 and mysql 5.0
what am i doing wrong, thanks.
It's inserting two rows because you're executing two INSERT statements. Each time you run an INSERT it does just that: inserts a row.
I'm guessing you wanted to create a single row with both the id and cv fields populated. The SQL syntax for that is INSERT INTO copy (id, cv) VALUES ('x', 'y');
So:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')",conn);
It's because two separate inserts are running. You can insert more than one value, try this:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id, cv) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')", conn);
You can comma separate the fields, and the values so it inserts into one record. Executing 2 insert commands will always create 2 records.
You didn't say which driver you're using so I'll use the documentation I found for dotConnect. I would try to use something along these lines (explanation of code below)
using( var conn = new MySqlConnection(#"connection string"))
using( cmd = new MySqlCommand("", conn) ){
cmd.CommandText = #"
INSERT INTO copy (id, cv)
VALUES (:name, :userContent)";
cmd.Parameters.Add("name", MySqlType.[correct type]]).Value = Page.User.Identity.Name;
cmd.Parameters.Add("userContent", MySqlType.[correct type], [column size]).Value = mainEditor.Content;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The use of the using construct is because MySqlConnection and MySqlCommand classes both implement the IDisposable interface so they need to be disposed of when you're done using them to avoid possible resource leaks.
The :name and :userContent is what I found in documentation for creating parametrized queries. This will allow the database driver to take care of escaping all of the special characters out of user input to avoid SQL injection attacks. This part is actually really important, there are some REALLY sophisticated SQL injection attacks out there, so there's a good chance simply escaping ' (as you were doing) isn't enough.

ASP Session value

I'm setting a Session of MM_CustomerID in my code and then further down the page I need to insert the value of that session into a table. But each time I try to do this it comes up with an Invalid column name 'varCustomerID'.
At the top of the page I have this code;
<%
set rscustomerid = Server.CreateObject("ADODB.Recordset")
rscustomerid.ActiveConnection = CmdAddCustomer.ActiveConnection
rscustomerid.Source = "SELECT ##IDENTITY as MaxCustomersID FROM Customers"
rscustomerid.CursorLocation = 2
rscustomerid.LockType = 3
rscustomerid.Open()
Session("MM_CustomerID")=rscustomerid("MaxCustomersID")
Session("MM_UserAuthorization") = "5"
%>
Then further down, i'm trying to set a variable of varCustomerID to be equal to the MM_CustomerID session;
<%
varCustomerID = Session("MM_CustomerID")
%>
And then try inserting the value of that variable varCustomerID into the Orders table as follows;
<%
'Insert record into Orders recordset when form is submitted
'and store the unique OrderID
'Version Date: 09 August 2009
set CmdAddOrder = Server.CreateObject("ADODB.Command")
CmdAddOrder.ActiveConnection = MM_dbconn_STRING
CmdAddOrder.CommandText = "INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (varCustomerID,0.00,3)"
CmdAddOrder.CommandType = 1
CmdAddOrder.CommandTimeout = 0
CmdAddOrder.Prepared = true
CmdAddOrder.Execute()
%>
I wondered if anyone might be able to help? Perhaps there's an easier way of just inserting the session value into the table, instead of creating a variable for it?
Thanks.
You need to change the sql command text to:
"INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (" + varCustomerID + ",0.00,3)"
However you could be vulnerable to SQL injection... really you should parametrise this query:
http://aspnet101.com/aspnet101/tutorials.aspx?id=1
You need to cast varCustomerID to a string for the query. Slight change to Paul's answer should get you working but like he says you need to be careful of injection attacks.
"INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (" & varCustomerID & ",0.00,3)"

Resources