The user enters the date as MM/DD/YYYY in a string and it needs to be formatted in C#/ASP.NET for insertion into a SQL Server 2008 R2 record. I understand I should convert it to a datetime and parameterize it into the query, but can't find an example of this.
What is the easiest way to do this?
Use DateTime.Parse and in your query add the re turned DateTime as parameter.
var date = DateTime.Parse(theString);
SqlCommand cmd = new SqlCommand("insert into xxx (theDateField) values(#param1)", con);
cmd.Parameters.AddWithValue("param1", date);
//execute your query and do what even you want.
I understand that question is answered but this might be also helpful
DateTime regDate = DateTime.MinValue;
if (txtDate.Text.Trim().Length > 0)
{
string[] ddmmyyyy = txtDate.Text.Trim().Split(new char[] { '-', '/' });
regDate = Convert.ToDateTime(ddmmyyyy[1] + "/" + ddmmyyyy[0] + "/" + ddmmyyyy[2]);
}
Now your date is ready you can insert in database using whatever method you like.
cmd.Parameters.AddWithValue("#RegDate", regDate);
or
SqlParameter paramRegDate = new SqlParameter("#RegDate", SqlDbType.DateTime);
selCmd.Parameters.Add(paramRegDate);
Related
I want to copy a selected date from a monthCalender control to a sqlite db in c#.
Tried to do it with ToString : Gave me this form of string (MM-DD-YYYY-00:00:00 AM) and a logic error
from sqlite.
Tried doing it with ToShortDateString: It gave me this string (MM-DD-YYYY).
No error from sqlite until checking the record again.This time the error was "string was not recognized
as a valid DateTime".
I know the date format for sqlite is YYYY-MM-DD.
Do I have to convert the string?
string startdate = monthCalendar1.SelectionRange.Start.ToShortDateString();
string query = $"UPDATE status SET user = {listBox1.SelectedValue}" +
$" , userbadge = {listBox2.SelectedValue} "+
$" , date = {startdate}" +
$" WHERE status.id = {index}";
openConnection();
SQLiteCommand com = new SQLiteCommand(query, connection);
com.ExecuteNonQuery();
closeConnection();
I think you can mitigate your problem simply by using Parameters:
command.CommandText =
#"
UPDATE status SET user = $user, userbadge = $userbadge, date = $startdate WHERE status.id = $index
";
command.Parameters.AddWithValue("$user", listBox1.SelectedValue);
command.Parameters.AddWithValue("$userbadge", listBox2.SelectedValue);
command.Parameters.AddWithValue("$startdate ", startdate );
command.Parameters.AddWithValue("$index", index);
According to this docu, the value will be saved as "yyyy-MM-dd HH:mm:ss.FFFFFFF".
The solution with the parameters resulted in the same error.
After searching a bit further I found out that maybe converting the string would
do the job. And yes it worked!!!
DateTime datetime = Convert.ToDateTime(startdate);
I am capturing the time in the text box (by using AJAX calender extender)
the time in the string is 12/10/2013, but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM.
I want to use the date to filter the records in the database using the query below. Please help
string date1 = txtDate1.Text;
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";
It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is.
In your circumstances, you can do this by using SqlParameters e.g.
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=#dateTime
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";
using (SqlConnection connection = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand(strQuery, connection))
{
cmd.Parameters.AddWithValue("#dateTime", date);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
}
}
Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. Failure to do this can leave you open to various exploitations such as SQL Injection.
Instead of DateTime object you can use Date object.
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime.
ex:
DateTime.Now.ToString("MM/dd/yyyy");
I have a MySQL database, there's a table which have column Time's Type is Nvachar(50) and its values is kind like this "05/09/2012 20:53:40:843" *(Month-date-year hour:mins:second:msecond)*
Now I want to query to get a record have Time after "10/05/2012 01:00:30 PM".
I had code in C# to converted it to "05/10/2012 13:00:30" before making a query.
My Query :
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
But i got no record. So please tell me how can I can make it return record have time after the time above ???
More Info My C# code :
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
var query = "SELECT * FROM " + tableName + " WHERE capTime > '" + date + "' LIMIT 0, 1";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
I'm so so so so so so sorry. I made a mistake the query must be
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
This query is successful return the record i need :)
But soemhow I have mistyped it into
SELECT * FROM ABCDFEGH WHERE capTime > '05-10-2012 13:00:30' LIMIT 0, 1
Sorry again, topic close. But tks for evveryone tried :)
I recommend using the DATETIME datatype instead of NVARCHAR. Store dates in YYYY-MM-DD HH:MM:SS format, which is the native DATETIME format recognized by MySQL.
Also use date literals in the same format.
Two reasons for this recommendation: First, DATETIME takes only 8 bytes, instead of up to 150 bytes which is the potential size of a multibyte 50 character varchar.
Second, the sort order of DATETIME will be the same as the chronological order. So if you create an index on the Time column, your > comparison can benefit from the index. Your query will be much faster as a result.
Use TIMESTAMPDIFF()
Schema
CREATE TABLE ABCDFEGH (`right` varchar(3), `time` datetime);
INSERT INTO ABCDFEGH (`right`, `time`)
VALUES
('Yes', '2012-10-02 13:00:30'),
('No', '2012-10-15 13:00:30');
SQL Code
SELECT * FROM ABCDFEGH
WHERE TIMESTAMPDIFF(MINUTE, time, '2012-10-05 13:00:30') > 0
LIMIT 0, 1
Explanation
TIMESTAMPDIFF() returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
Fiddle: http://www.sqlfiddle.com/#!2/244cc/1 datetime
Fiddle: http://www.sqlfiddle.com/#!2/063b3/1 varchar(50)
PS1: Time may be a reserved word. Please avoid using it. Else use it with backticks (`).
PS2: The format of time is YYYY-MM-DD not the reverse.
First, why did you save the dates as NVARCHAR? If you are still able to change it to DATETIME datatype and all of the records on it, much better.
But if not, you can use STR_TO_DATE.
SELECT *
FROM tableName
WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') >
STR_TO_DATE('05/10/2012 13:00:30', '%c/%d/%Y %H:%i:%s')
See SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE Formats
UPDATE 1
and your query is vulnerable with SQL Injection. To avoid from it
Parameterized your query
code snippet,
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
String query = "SELECT * FROM " + tableName + " WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') > STR_TO_DATE(#dateHere, '%c/%d/%Y %H:%i:%s')";
using (MySqlConnection connection = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
command.Parameters.AddwithValue("#dateHere",date)
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
catch(MySqlException e)
{
// do something here
// don't suppress the error
}
}
}
I have a query which fetches the information from sql server on datematch.
I have searched a lot about SQL Server date string, I just want to match with the date and get the data from database. Also I am using SQL Server 2005, I want to fetch the date and take the time out of it?
Can anybody help me in that... I am new to C#
Here is my query.
return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString();
use the sql server CONVERT function to convert the input date param to time
Change your query to accommodate any one of the below CONVERT function
SQL query to convert Time format into hh:mm:ss:
select convert(varchar, <<dateparam>>, 108)
SQL query to convert Time format into hh:mi:ss:mmm(24h):
select convert(varchar, <<dateparam>>, 114)
You should always use parameters when querying a database - whether or not SQL injection is possible, it's just plain good practice to use parameters, and it solves some of the thorny how many quotes and which kind do I need here to make it a valid SQL statement questions, too.
So try something like:
string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " +
"WHERE E_ID = #ID AND Date = #Date";
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// set up parameters
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = E_ID;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now.Date;
// open connection, read data, close connection
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
// read your data
}
rdr.Close();
}
conn.Close();
}
I'm using Sql Compact3.5 as my DB with C# .NET In different systems i'm getting the datetime format differently. In an Windows XP it's retrieving the datetime in the format : MM-dd-yyyy HH:mm:ss and in Media center it's retrieving in the format : MM/dd/yyyy hh:m:ss. Is there any way to make the datetime format free from culture or can i set the datetime format in sql compact so let it be any PC it'll use that format only???
Example :
//TimeOfCall is passed as String using the format DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeCommand SqlceCmd = new SqlCeCommand(
"Insert into myreports(TimeOfCall,Status) values(?,?)", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall));
SqlceCmd.Parameters.Add(new SqlCeParameter("#Status", strStatus));
int RowsaAffected = SqlceCmd.ExecuteNonQuery();
con.Close();
return RowsaAffected;
}
}
While Rertiving the record the query is used in this way :
//FromTime and ToTime are passeed in the same format as while storing
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeDataAdapter SqlceDA = new SqlCeDataAdapter("Select TimeOfCall from myreports where TimeOfCall between '" + strFromTime + "' and '" + strToTime + "' order by TimeOfCall", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceDA.Fill(dtReports);
con.Close();
return dtReports;
}
}
I hope it's clear
Ok, from the code, you're basically doing the right thing the wrong way.
The good news is that you're using parameters - that's exactly right - however you don't need actually don't want to convert the date to a string before setting the parameter value.
Simplest should be to change SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall)); to SqlceCmd.Parameters.AddWithValue("#TimeOfCall", timeOfCall)); where timeOfCall is a DateTime value.
The same applies to the status if that's not natively a string.
If you want to be more explicit about types create the parameter first defining the type and then set it.
For your selection query do the same thing, replace your string concatenation with parameters #fromTime and #toTime and set the parameters directly from the appropriate DateTime values