C# Generate Query to Compare DateTime with SQL Nvarchar date Column - c#

I tried to get result depending on two dates which the user checked.
I have two datetimepicker controls.
I want the user to chooses the "from" date and "to" date,
then the query get specific result.
leaving_time column type is nvarchar
This is my query:
SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN '"+dateTimePicker1.Checked.ToString()+ "' AND '" + dateTimePicker2.Checked.ToString() + '"
Where is the mistake?

You should write parameterized queries and not using string concatenation for passing the parameters, in order to create a sql command. Using string concatenation makes you code vulnerable to sql injections.
var cmdText = #"SELECT ...
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN #StartDate AND #EndDate";
var sqlCommand = new SqlCommand(cmdText, connection);
sqlCommand.Parameters.AddWithValue("#StartDate", dateTimePicker1.Value);
sqlCommand.Parameters.AddWithValue("#EndDate", dateTimePicker2.Value);
where connection is your sql connection object.

Try to use dateTimePicker1.Text in dateTimePicker1_ValueChanged event where you are using dateTimePicker2.Checked that return true or false not the value of date

Checked is a boolean property, and it is not the date. You need to use the Value Property. It is better to add parameters and explicitly specify the type so that the date format conflict is solved.
Edit: If column type in SQL server is NVARCHAR and of format MM/dd/yyyy, you need to use ONVERT(DATETIME, leaving_time, 101):
conn.Open();
SqlDataAdapter dataAdapter =
new SqlDataAdapter("SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year "
+ "FROM dbo.Hodor_data where CONVERT(DATETIME, leaving_time, 101) "
+ "BETWEEN #p1 AND #p2", conn);
SqlParameter fromDate = new SqlParameter("#p1", SqlDbType.DateTime2);
fromDate.Value = dateTimePicker1.Value;
SqlParameter toDate = new SqlParameter("#p2", SqlDbType.DateTime2);
toDate.Value = dateTimePicker2.Value;
dataAdapter.SelectCommand.Parameters.Add(fromDate);
dataAdapter.SelectCommand.Parameters.Add(toDate);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close()
You should really consider changing the type of column leaving_time to be a DateTime column. This will make your life easier in querying. I can't really see any advantage of storing these values as text.

Related

Checking if current date exists in database using c#

I have a table which I want to insert data in it only once in a day
and to implement that I want to check if current date already exists in
the database by writing these lines
DateTime date = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `attendances` WHERE
`lecture_id` = '" + lecture_id + "' " +
" AND `date` = '"+date.ToShortDateString()+"' ",con);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
MessageBox.Show("you can't insert");
else MessageBox.Show("you can insert");
The date is inserted to the database in this format xxxx-xx-xx although using the same method for inserting, and date.ToShortDateString() returns the date in this format
xxxx/x/x .
I checked inserting the date manually in the correct format but that also didn't work, I also tried using the DATE function in sql but that didn't work either.
Just apply format string date = DateTime.Now.ToString("yyyy-MM-dd")
And do not call ToShortDateString() in your SQL query
You also should use SqlParameter as your code is vulnerable for SQL injection attack.
You could also avoid using .NET's DateTime and use MySql's NOW() or UTC_DATE() instead within your query, which may be better; if the region of your code and db reside in different timezones.
i.e.
[...] " AND `date` = DATE(NOW()) ",con);

MySQL C# Insert query Server timestamp

I have a C# program and I want to run a MySQL query that insert a record. In this record I have a timestamp field that MUST BE the server timestamp, not the client timestamp.
So, I write this:
start_session = new MySqlDataAdapter("INSERT INTO CUBE_WORKTIME(ID_WORKTIME,
ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,
ID_CDC_FK, CAUSALE, LAST_EVENT)
VALUES ('', '"+ idrisorsa_global + "', DATE(NOW()),NOW(),
NULL, '"+ IDCDC +"', 'Login', 'Y')", connection);
DataTable start_session_dataset = new DataTable();
start_session.Fill(start_session_dataset);
This query works well, the ID_RISORSA_FK and IDCDC fields are correct. But the date and the datetime are 0000-00-00 and 0000-00-00 00:00:00.
I also tried adding the quotes, but no effects.
Any ideas?
The first thing to change is the use of an MySqlDataAdapter to just insert a record. While this could work it is not the correct class to use for this work. A simple MySqlCommand is the correct object to use and with a lot less of infrastructure required
The second thing to change is the way in which you build your sql query. Do not concatenate together strings to form an sql command but use Parameters. This avoid Sql Injection and parsing problems.
So your code could be rewritten as
string cmdText = #"INSERT INTO CUBE_WORKTIME
(ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,ID_CDC_FK,
CAUSALE, LAST_EVENT) VALUES (#risorsaID, CURDATE(), CURTIME(),
NULL, #cdcID, 'Login', 'Y')";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.Add("#risorsaID", MySqlDbType.Int32).Value = idrisorsa_global;
cmd.Parameters.Add("#cdcID", MySqlDbType.Int32).Value = IDCDC;
int rowsInserted = cmd.ExecuteNonQuery();

update the datetime value of a table MS SQL from ASP.NET code

I've a table "user_info" with fields and datatypes.
user_id || user_reg_date [datetime] NULL DEFAULT
(getdate()) || user_next_visit_date [datetime] NULL
here user_reg_date is default value, so the format is :: 2015-06-02 12:17:12.307
for the field, user_next_visit_date I've to update it from ASP.NET code, same format as user_reg_date.
string queryString = "UPDATE user_info SET user_next_visit_date = ???
WHERE user_id ='" + user_id + "'";
how to set the value of user_next_visit_date [datetime] with the current date time in the same format as user_reg_date. I frequently face problem with datetime values inserting from ASP.NET to database.
A DateTime has no format. Updating it is easy as cake with parametrized queries:
SqlCommand query = new SqlCommand();
query.Connection = ...
// Parameters start with #
string queryString = "UPDATE user_info SET user_next_visit_date = #someDateVar WHERE user_id=#userid";
query.CommandText = queryString;
// Date parameter
SqlParameter dtPar = new SqlParameter("#someDateVar", SqlDbType.DateTime, 0);
dtPar.Value = DateTime.Now; // or any DateTime you have
query.Parameters.Add(dtPar);
// Id parameter
SqlParameter idPar = new SqlParameter("#userId", SqlDbType.Int, 0);
idPar.Value = user_id;
query.Parameters.Add(idPar);
// Execute
query.ExecuteNonQuery();
This has the side effect that SQL injections are no longer possible.
In fact, I use this add-a-parameter part so often that I would recommend shortcuts which make them oneliners.
To update with the current date just use getdate():
string queryString = "UPDATE user_info SET user_next_visit_date = getdate() WHERE " ...
Remember to parametrise your queries as suggested in other answers.
You can use datetime object and use like this
DateTime dt = DateTime.now;
this dt object you can pass in your update statement.

compare DateTime in SqlCommand

I have a simple SqlCommand in which I want to return all records within a specified DateTime range. (both Date and Time are involved)
var dataReader = new SqlCommand(
#"Select RecordID from RecordTable
where RecordTable.WorkingDT between '"+ _startDt +"' and '"+ _endDt +"'",
_sqlConnection).ExecuteReader();
how do I have to set the values for _startDt and _endDt?
You can try this:
var dataReader = new SqlCommand(
#"Select RecordID from RecordTable
where RecordTable.WorkingDT between '"+ _startDt.ToString("yyyy-MM-dd HH:mm:ss") +"' and '"+ _endDt.ToString("yyyy-MM-dd HH:mm:ss") +"'",
_sqlConnection).ExecuteReader();
Where _startDt and _endDt are type of DateTime.
If you add them as proper parameters in your command, you don't need to worry about formatting. The added benefit of getting into the habit of using these is that you don't have to worry about SQL injection when you were to supply strings as parameters.
Have a look at http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
It shows how to use parameters in your queries. I don't think it needs to be spelled out completely.
An example (copy/pasted from the site):
// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = #City", conn);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#City";
param.Value = inputCity;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
// get data stream
reader = cmd.ExecuteReader();
And yes, defining the parameters can be done shorter that 3 lines per parameter. But that's left up to the reader.
#kmatyaszek, While commonly used, the "yyyy-mm-dd HH:mm:ss" date format is not guaranteed to be unambiguously parsed by SQL server. If you must create SQL from concatenating strings (not necessary in this case as René has shown) then you should use the ISO8601 format, which is just the same but with a T in the middle: "yyyy-mm-ddTHH:mm:ss".
http://msdn.microsoft.com/en-us/library/ms190977%28v=sql.90%29.aspx
"The advantage in using the ISO 8601 format is that it is an
international standard. Also, datetime values that are specified by
using this format are unambiguous. Also, this format is not affected
by the SET DATEFORMAT or SET LANGUAGE settings."
For a demonstration why, try this rerunnable Sql script.
if object_id('tempdb..#Foo') is not null drop table #Foo;
create table #Foo(id int, d datetime)
-- Intend dates to be 12th Jan.
set dateformat ymd
insert into #Foo(id, d) values (1, '2012-01-12 01:23:45') -- ok
insert into #Foo(id, d) values (2, '2012-01-12T01:23:45') -- ok
set dateformat ydm
insert into #Foo(id, d) values (3, '2012-01-12 01:23:45') -- wrong!
insert into #Foo(id, d) values (4, '2012-01-12T01:23:45') -- ok
select * from #Foo order by id
if object_id('tempdb..#Foo') is not null drop table #Foo;

SQL Server date store in c#

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

Categories