Convert date in textboxes to date in SQL Server - asp.net

I am working in ASP.NET as front end and SQL Server 2012 as backend. In ASP.NET, the user enters a date in 3 textboxes in the format DD/MM/YYYY.
Now I have concatenated these textbox values into a string. In SQL Server, I want to save this date into column DOB with a data type of DATE.
Below is concatenated string in ASP.net
string strDOB = txtYY.Text + "/" + txtMM.Text + "/" + txtDD.Text;
How can I now save this strDOB in SQL Server?

Stop using strings. Besides the advice in the comments to use a dedicated picker control, the next best advice is to parse those strings into integers (briefly), then construct a DateTime object from that and then do not let it get converted back into a string. It's when people let extra string/date conversions happen that they introduce formatting problems. So get the value:
var year = Int32.Parse(txtYY.Text);
var month = Int32.Parse(txtMM.Text);
var day = Int32.Parse(txtDD.Text);
var dob = new DateTime(year,month,day);
And then pass it to SQL Server:
var cmd = new SqlCommand(...);
cmd.Parameters.Add("#DOB",SqlDbType.Date).Value = dob;
And make sure that your query uses the parameter #DOB wherever you want to use that value.

Try this:
UPDATE [Table] SET [Column] = '' + strDOB + ''
Be careful, though... this hasn't been sanitized to guard against SQL Injection. I've only demonstrated the direct answer to your question, nothing more.
As a best practice, you should never concatenate together unchecked user input and store the result in a column. Techniques for preventing this are outside the scope of this Q&A, but are easily discovered with a minimal amount of searching.
--EDIT--
I defer to Damien's answer on this one. I agree with his syntax suggestions.

Related

Strange issue with Date.Parse / ParseExact not altering date (ASP.Net)

I have a bit of a head scratcher with the Date.Parse /ParseExact functionality in VB.
To surmise, I have an ASP.Net 4.0 app, on one of the pages there is a calendar control which the user chooses a date and time, these are fed into a string (strReqDeadline) which takes the following European / UK date time format: dd/MM/yyyy HH:mm:ss.fff
So for example the contents of strReqDeadline would be: 29/03/2013 16:30:00.000
I then need to insert this into a SQL datetime column, so obviously it needs converted from UK to the US/datetime format. I've been attempting to do this with Date.Parse and Date.ParseExact with no success. The following should work according to the research I've done:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate = As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
However, what actually happens at runtime is bizzare, the Date.ParseExact function trims off the fractal seconds from the time (as far as I can see it shouldn't be doing this because the filter specifies .fff), and otherwise leaves the entire string completely unchanged.
So, if the value of usDate is output, it appears as follows: 29/03/2013 16:30:00
What it should contain is datetime: 3/29/2013 4:30PM
The really strange thing is if I put a watch on usDate and start the app, in the development environment its value shows as #3/29/2013 4:30PM#, both in the watch list and when hovered over in the source window, but any form of output displays the original string, just minus the fractions of second, and doesn't convert to datetime.
From what I read the 'InvariantCulture' specification should negate any locale specific issues with output, but just in case this were the issue I also tried specifying an explicit local culture with System.Globalization.CultureInfo.CreateSpecificCulture("en-GB") (tried fr-FR too), but this makes no difference. The Windows regional settings on both the client and server are set to UK if this bears any relevance.
Maybe I'm missing something very obvious but I just can't see why I'm getting this output, Date.ParseExact doesn't throw any exceptions or complain about the string not being recognised, but I'm struggling to understand why it just removes the fraction seconds and does nothing else, especially since the input spring matches the specified mask exactly.
I'd be very interested to hear if anyone else has experienced an odd issue like this and what you did with it!
Thanks :)
EDIT: Full code with SQL section is as follows:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
'SQL
Dim con As New Data.SqlClient.SqlConnection("data source=XXXXX;initial catalog=YYYYY;Integrated Security=True")
Dim cmd As New Data.SqlClient.SqlCommand()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Requests (ReqOwnerID, ReqDeadline, ReqStatus)" _
& "VALUES ('" & UserID & "', '" & usDate & "', '1')"
con.Open()
Dim NewReqID = cmd.ExecuteScalar()
con.Close()
'
Why is it you thin it is not working? These are all the same underlying date/time:
29/03/2013 16:30:00.000
29/03/2013 16:30:00
3/29/2013 4:00PM
You cannot rely on what hovering over a non-string variable shows to determine its inner value. All you are seeing is the evaluation of ToString(). If you want a String to show the fractions seconds, then you need to call ToString() and specify the format "dd/MM/yyyy HH:mm:ss.fff". By default a DateTime type if not going to show your fractions seconds when you convert to a String.
If you are not using parameters (and you should be) then your final SQL statement after injecting the DateTime would be something like this:
INSERT INTO MyTableWithDate
(column1
,column2
,MyDateCol)
VALUES
('a'
,'b'
,'20130329 16:30:00.557')
As I mentioned before, a Date datatype is not String. It's an object (or a rather a DateTime structure, by I digress). You must call the correct ToString() meth0d.
Try using this withing your SQL string:
& "VALUES ('" & UserID & "', '" & usDate.ToString("yyyyMMdd HH:mm:ss.fff") & "', '1')"
Of course, there is little point converting a string to Date object to immediately convert it back to a string again, but this code should work.
usDate is an object of type DateTime, and it appears to be storing the correct value. When you are inspecting it, you are seeing a string representation of that datetime value. It doesn't contain either 29/03/2013 16:30:00 or 3/29/2013 4:30PM, those are just two valid representations of what it contains.
You say
any form of output displays the original string
This is not true. In fact you have control over how it is output when you call ToString(), where a format can be specified
What you are doing looks correct i.e. using Date.ParseExact to convert a date in UK format to a Date type. The issue you are having is that when it displays this as a string it is displaying it in your local culture (the debugger appears to always want to display in US format), but the Date you have set is correct.

ASP.NET saving empty date value in SQL Server database with parameters

I have a web forms application which allows to update database columns. One of the database columns is Finish Date which is of date datatype in the SQL Server database.
I use SQL query with parameters and textbox to provide the new value for the finish date.
This is a code which gets me the value of the date from a text box within the grid:
TextBox tFD = (TextBox)grdProjectUpdate.Rows[e.RowIndex].Cells[11].FindControl("proFDTextBox");
then I use a parameter:
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = tFD.Text.Trim();
to update the value using this SQL statement:
UPDATE PMSprojects SET proFD = #proFD ,...
This solution works fine whenever there is an actual date provided. However, it does not save nulls. If I provide an empty string, it is being converted into 1900-01-01 date, even though the column in the database allows nulls.
How could I solve this issue and save null to the database?
You have to write code around this to handle, and pass DbNull.Value when the value is null.
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = (tFD.Text.Trim().Length > 0) ? (object)tFD.Text.Trim() : DbNull.Value;

How can I create a LINQ statement where the table name (FROM) and column name (SELECT) is variable?

In my programming task I've gone down a dark alley and wished I hadn't, but there is no turning back now.
I'm building up a SQL statement where the table name, column name and id value are retrieved from query string parameters i.e. ("SELECT [{0}] FROM [{1}] WHERE [Id] = {2};", c, t, id)
But it isn't as bad as it looks, I'm protected:
Only authenticated users (i.e. signed in users) can execute the Page_Load
I'm checking that both the table and the column exists beforehand
(using GetSchema etc.)
I'm checking that the Id is an integer beforehand
All my tables have Id columns
The database connection is reasonably secure
The field value is expected to be of type NVARCHAR(4000) or NVARCHAR(MAX) so I'm avoiding ExecuteScalar and I'm trying out LINQ ExecuteQuery because I like LINQ. But I'm a bit out of my depth again.
I've got this far:
Dim db As New MyDataContext
Dim result = db.ExecuteQuery(Of ITable)("SELECT [{0}] FROM [{1}] WHERE [Id] = {2};", c, t, id)
Is this the right way to go?
How do I get first row and first column value?
Is there a better alternative?
P.S. It's a SQL Server 2005 database
Any help appreciated.
Thanks.
SQL Server requires the tables ans columns to be statically known. You can't provide them using command parameters. You can't say
select * from #tableName
because the table name can't be a variable.
You need to build the SQL string with C# ensuring proper escaping of identifiers. Escaping works like this:
var escaped = "[" + rawUntrustedUserInput.Replace("]", "]]") + "]";
This is safe.

Date Time format problem in sql server

I have an application in asp.net which worked fine untill recently when i changed the datetime format in Regional and Language Settings in Control Panel.
The date time format was default when i installed XP. I chose Indian standard time while installing XP.
I changed the date time format to dd/MM/yyyy HH:mm:ss. And my application started to throw an exception whenever i tried to insert any datetime in to the table.
The exception i get is:
System.Data.SqlClient.SqlException: Error converting data type varchar to datetime.
Please help me on this
Hard to know exactly what's going on without seeing the code that's throwing. However, if you need to communicate dates to SQL Server, it is generally good practice to use the ISO 8601 standard for representation because it is unambiguous and locale-independent. The most important formats are:
yyyy-MM-dd for dates
hh:mm:ss for time
yyyy-MM-dd hh:mm:ss for date/time
My guess is that you have a query that's sending over dates in the current locale, and the locale on the server does not match.
Edit: And for the record, this doesn't preclude anything that Rob said in his answer, i.e. try to avoid passing hard-coded dates or hard-coded SQL at all. This only applies if you need to for some reason.
Edit 2: I've been informed that the yyyy-MM-dd format can still be wrong for some locales; so instead of this, if you need to pass in a literal date string, you should instead use yyyyMMdd.
As per my comment, you'll probably want to make sure you're using code that behaves in a similar way to the code below (i.e. using parameters rather than string concatenation)
var myConnectionString = "connection string goes here";
var myDateValue = DateTime.Now;
using (var connection = new SqlConnection(myConnectionString))
{
using (var command = new SqlCommand("SELECT COUNT(1) FROM dbo.table WHERE datecolumn = #datevalue", connection))
{
var dateValueParameter = new SqlParameter("#datevalue", myDateValue);
command.Parameters.Add(dateValueParameter);
var result = Convert.ToInt32(command.ExecuteScalar());
}
}
Try adding "Current Language=YourLanguage" to the SQL server connection string. Where YourLanguage is the language you want SQL to use when reading values such as the dates.
You can see a list of all languages supported by SQL by executing the following SQL command:
select * from master.dbo.syslanguages

SQL statement merging/simplifying

I'm not sure whether my SQL code and practise here is any good, so hopefully someone could enlighten me. In order to try and separate my DAL from the Business layer, I'm not using an SQLDataSource on the page. Instead, I've created a gridview to display the results and called an SQL command to retrieve results. I have the following SQL command:
string CommandText = "SELECT User.FName + User.Surname, Product.Name, Product.Quantity, Product.Price FROM User, Products WHERE Product.UserID = User.UserID";
The results are then loaded into a datareader and bound to the gridview control. This works fine. However, is the SQL statement inefficient? I've noticed some SQL statements have square brackets around each field, but when I try and put it around my fields, no results are displayed.
I'm also trying to merge the firstname and surname into one column, with a space between them, but the above doesn't put a space between them, and I can't seem to add a space in the SQL statement.
Finally, this all occurs in the code-behind of the shopping-cart page. However, is it insecure to have the connectionstring and above SQL statement in the codebehind? My connectionstring is encrypted within the web.config file and is called via the Configuration API.
Thanks for any help.
Firstly, using square brackets is optional in most cases (IIRC, there are very few instances where they are actually necessary, such as using keywords in the statement). Square brackets go around each identifier, for example,
SELECT [Server_Name].[Database_Name].[Table_Name].[Field_Name], ...
Secondly, to add a space, you can use SELECT User.FName + ' ' + User.Surname. You also might want to alias it - SELECT User.FName + ' ' + User.Surname AS [name]
Thirdly, keep the connection string in the web.config and encrypt it using a key.
Finally, you may want to consider introducing a data access layer into the project that can return objects from your datasource (might be worth having a look at NHibernate, LINQ to SQL or Entity Framework for this). You can then bind a collection of objects to your GridView.
Long time no SQL usage, but I don't see a problem with your query, as long as the database is designed well. To concatenate two string columns use something like this:
User.FName + ' ' + User.Surname AS UserName
Simply add a space between two strings.
As for security concerns: all other people can see is a rendered web page. If you don't expose connection string nor queries in the rendered HTML/JS code (like in comments etc.), you should not worry. The connection string stored in web.config and database structure visible in queries in server code are safe as long as the server is safe.
Try this:
string CommandText = "SELECT
User.FName + ' ' + User.Surname AS Fullname,
Product.Name,
Product.Quantity,
ProductDetail.Price
FROM
User, Products
WHERE
Product.UserID = User.UserID";
Best wishes,
Fabian

Resources