SQL Server date store in c# - 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();
}

Related

Select records by date range in Access Table From C# Application

I am developing a simple C# application for retrieving particular records from one table and insert in to another table in MS Access. Also this task ha s to be performed daily using Windows task scheduler.
The selection of records has to be done on date range to retrieve "Today created records".
My application works between [ DateTime.Today.AddDays(-100) to DateTime.Today.AddDays(0)] but, it wont work for DateTime.Today.AddDays(0) to DateTime.Today.AddDays(1)
I have done so far below.
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Tom\\Dropbox\\P2002\\p2002.mdb;Persist Security Info=True");
OleDbCommand cmd = con.CreateCommand();
con.Open();
Console.WriteLine("Connected...");
cmd.CommandText = "Insert into New1 ([B ID], [Dat], [Sum]) SELECT BID, Dat, Summe FROM Bestellung Where [Datum] BETWEEN #" + DateTime.Today.AddDays(0) + "# AND #" + DateTime.Today.AddDays(1) + "#" ;
Console.WriteLine(DateTime.Today.AddDays(0));
Console.WriteLine(DateTime.Today.AddDays(1));
cmd.ExecuteNonQuery();
Console.WriteLine("Record Submitted");
con.Close();
Probably your problem is caused by the automatic conversion from the datetime values (Today and Today.AddDays(1)) into a string when you concatenate those values.
When you query MS Access on date fields with string constants, it wants the strings formatted in the "MM/dd/yyyy" way, and thus you should return a string formatted in that mode when you use it to represent your date values. Like so:
... Where [Datum] BETWEEN #" + DateTime.Today.ToString("MM/dd/yyyy") ...
(Note that I removed the Today.AddDays(0) because it makes no sense)
but there is another way a lot more safe because it avoids any possible Sql Injection attack and more flexible because it doesn't force you to concatenate strings and use formatting options. This method is called "Parameterized query"
Here how to rewrite your code to use parameters.
using(OleDbConnection con = new OleDbConnection(.....))
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
Console.WriteLine("Connected...");
cmd.CommandText = #"Insert into New1 ([B ID], [Dat], [Sum])
SELECT BID, Dat, Summe
FROM Bestellung
Where [Datum] BETWEEN #d1 AND #d2";
Console.WriteLine(DateTime.Today.AddDays(0));
Console.WriteLine(DateTime.Today.AddDays(1));
cmd.Parameters.Add("#d1", OleDbType.Date).Value = DateTime.Today;
cmd.Parameters.Add("#d2", OleDbType.Date).Value = DateTime.Today.AddDays(1);
cmd.ExecuteNonQuery();
Console.WriteLine("Record Submitted");
}

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

How do I store 'date' in SQL Server 2005 using C# query

an error while storing date in DB (SQL server 2005) using C#
I am using,
DateTime mydate = DateTime.Now;
insert into mytablename (appdate) values('"+mydate.ToShortDateString()+"');
bt its showing error when I run the query
also tried,
mydate.ToShortDateString().ToString("dd-MMM-yyyy HH:mm:ss") in C# , still showing error in editor only.
How do I store 'date' in SQL Server 2005 using C# query
Use parameterized SQL, and set the value into the parameter:
string sql = "insert into tablename (appdate) values (#appdate)";
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#appdate", SqlDbType.DateTime).Value
= DateTime.Now;
int rowsInserted = command.ExecuteNonQuery();
// TODO: Validation of result (you'd expect it to be 1)
}
}
You should always use parameterized SQL when you have data to include in the request to the database. This avoids SQL injection attacks and data conversion issues, as well as keeping your code cleaner.
You should also consider whether you really want it to be the local date/time or the UTC date/time. For example, you might want to use DateTime.UtcNow instead.
Your query tries to insert a string in a DateTime field. And of course it doesn't work.
The correct way to insert is through a parametrized query like this
string insertSQL = "insert into mytablename (appdate) values(#dt)";
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#dt", mydate);
cmd.ExecuteNonQuery();
Here I assume that the connection is already initialized and opened

Search datetime in MySQL

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
}
}
}

Categories