Select oracle date column using C# - c#

I am trying to select data from my Oracle database BY DATE using C#. However I am always getting an empty data set although the same query string works just fine in Oracle SQL Developer
String Query = "Select position_date from position";
OracleDataAdapter adapter = new OracleDataAdapter(Query, ocon);
adapter.Fill(ds, "table"); //where ds is a dataset
PrintDataSet(ds);
returns
3/8/2011 12:00:00 AM.... and more
However, when I change my query to below, then there is no output!
String Query = "Select position_date from position
where to_char(position_date, 'mm-dd-yyyy') = '05-17-2012'"
This query works fine in oracle sql developer. I've also tried trunc(sysdate) but nothing seems to work! :(

select * from position where trunc(position_date) = to_date('05-17-2012', 'mm-dd-yyyy')
worked.
Thanks.

If your dates have no time component (and if that is so then guarantee it with a check constraint), then:
Select position_date
from position
where position_date = date '2012-05-17'
Otherwise:
Select position_date
from position
where position_date >= date '2012-05-17' and
position_date < date '2012-05-17' + 1

Related

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

Using WHERE clause with csv files ADO.NET / C#

i have a little problem. I'm using a csv file as database and i'm asking it with ADO.NET's OLEDB funcions.
I want to select only rows where column "DATA" is included between two datas, like this:
String conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\;
;Extended Properties='text;HDR=Yes;Format=Delimited(;)';";
OleDbConnection cn = new OleDbConnection(conn);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [mydb]", cn);
OleDbDataAdapter daAd = new OleDbDataAdapter();
daAd.SelectCommand= cmd;
cn.Open();
DataTable dt = new DataTable();
daAd.Fill(dt);
DateTime mydata= Convert.ToDateTime("01/01/1990");
DateTime mydata2= Convert.ToDateTime("01/01/2000");
Nothing wrong until now, but when i change
"SELECT * FROM [mydb]"
With
"SELECT * FROM [mydb] WHERE DATA>= '"+ mydata.Date +"' AND DATA<='"+ mydata2.Date +"'
I have an error saying "Syntax error (missing operator) in query 'WHERE DATA=> mydata AND DATA<= mydata2'.
I really don't know how to solve it.
More info: .CSV file is formatted like this:
DATA;INFO1;INFO2;INFO3
01/01/1990;1;2;3`
And into schema.ini is this :
[mydb.csv]
Format=Delimited(;)
ColNameHeader=True
DateTimeFormat=dd-MM-yyyy
Col1=DATA DateTime
Col2=info1 Long Width 3
Col3=info2 Integer
Col4=info3 Integer
EDIT :
I'm running a x86 Seven, i read that for solve JET driver's incompatibility is sufficient the schema.ini file, hope i'm right.
Well, this:
SELECT * FROM [mydb] WHERE DATA=> mydata AND DATA<= mydata2
is clearly invalid SQL. Perhaps you meant:
SELECT * FROM [mydb] WHERE DATA>= mydata AND DATA<= mydata2
(You used => for "greater than" rather than >=.)
I think you mean this:
SELECT * FROM [mydb] WHERE DATA >= mydata AND DATA <= mydata2
You just got the => the wrong way round!
UPDATE AFTER OP's CORRECTION
Is it due to your schema.ini? You seem to have the wrong DateTimeFormat:
DateTimeFormat=dd-MM-yyyy
Shouldn't it be:
DateTimeFormat=dd/MM/yyyy
SECOND UPDATE
Change you mydata to the following:
"SELECT * FROM [mydb] WHERE DATA >= '" +
mydata.ToString("dd/MM/yyyy") +
"' AND DATA <= '" + mydata2.ToString("dd/MM/yyyy") + "'"
Try
SELECT * FROM [mydb] WHERE DATA >= mydata AND DATA <= mydata2
Note the order of "<" and "=" in the first comparison.
Because of i'm quering a csv I can't use sql's functions(errors says they don't exist) not even compare my DATA with string. If i put in the query an unquoted date it works, but i don't respect the WHERE clause, selecting all records.
Query seems to doesn't work only for DateTime format, so i'll put my DATA in a yyyyMMdd Integer format.It's the only alternative I've in mind, still don't know why can't search with Datetime fields.

Transact SQL date query returning no results

From my code, I call an SP using:
using (var cmd = new SqlCommand("sp_getnotes"))
{
cmd.Parameters.Add("#ndate", SqlDbType.SmallDateTime).Value
= Convert.ToDateTime(txtChosenDate.Text);
cmd.CommandType = commandType;
cmd.Connection = conn;
var dSet = new DataSet();
using (var adapter = new SqlDataAdapter { SelectCommand = cmd })
{
adapter.Fill(dSet, "ntable");
}
}
The Stored Procedure itself runs a simple query:
SELECT * FROM tblNotes WHERE DateAdded = #ndate
The problem is no records are returned! DateAdded is a smalldatetime column.
When I change the query to the following, it works:
SELECT * FROM tblNotes WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, DateAdded))) = #ndate
Why is this happening? This change affects the entire application and I'd like to find the root cause before getting into changing every single query... The only changes we made are to use parameterized queries and upgrade from SQL Server 2005 to 2008.
TIA.
smalldatetime has a time portion which needs to match as well.
Use this:
SELECT *
FROM tblNotes
WHERE dateAdded >= CAST(#ndate AS DATE)
AND dateAdded < DATEADD(day, 1, CAST(#ndate AS DATE))
SQL Server 2008 and above also let you use this:
SELECT *
FROM tblNotes
WHERE CAST(dateAdded AS DATE) = CAST(#ndate AS DATE)
efficiently, with the transformation to a range performed by the optimizer.
SQL Server 2008 now has a DATE data type, which doesn't keep the time porttion like SMALLDATETIME does. If you can't change the data type of the column, then you'll have to truncate when doing the compare, or simply cast to DATE:
SELECT *
FROM tblNotes
WHERE cast(dateAdded as date) = #ndate
I don't know SQL Server but from Oracle experience I'd suspect you're comparing a date time with a date, eg 01/01/2012 01:01:01 against 01/01/2012.

Issue with sql where clause when using datetime

Can anyone help me out with this query i m trying to execute,
static public DataTable GetAllCustomers()
{
string sql = "Select * from [project] where [condition] = 0 AND [Time] < '" + DateTime.Now + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
It returns nothing
Any ideas where i am getting the query wrong.
Putting DateTime's into SQL Strings is a recipe for disaster thanks to formatting and locations. Change your sql line to:
string sql = "Select * from [project] where [condition] = 0 AND [Time] < GetDate()";
This will use the servers own current date time in whatever format it is expecting.
If you absolutely need to do things client side then use SqlCommand and instead of adding DateTime as a string put a "Time < #" and then add the DateTime as a command parameter. That will avoid formatting problems at least.
Did you know SQL server has a built in time function. Try this:
string sql = "Select * from [project] where [condition] = 0 AND [Time] < GETDATE()";
or if you want date in UTC do this:
string sql = "Select * from [project] where [condition] = 0 AND [Time] < GETUTCDATE()";
This way you do not have any string concatinations in code.
Could you answer the following:
Which part is coming back nothing?
Is [Time] a DATETIME data type or similar (ie: not text)

Compare two Datetimes one from Datetimepicker and one from MySql Database

I have a strange problem...I have a MySql db with some columns and one of the column is date_purchased which is of type date_time.
I am using C# and made a DatetimePicker and user selects a date.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
varDate = dateTimePicker1.Value;
}
Now the problem is I have to compare the two datetimes (one from the database and one from the User) and I should display the records that are less than the date selected by the user(varDate).
select * from orders where date_purchased < = '" + varDate + "'";
I am executing this query but i am getting an exception
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '12/25/2011 8:01:31 PM'' at line 1
I wrote the connection string and all and I am struck at the query.
Any Help will be much appreciated...
Thanks,
Subash
You have not given any details on what you are using to run the select query; however, if you are using the connector provided by Mysql (Connector/Net) then you should be using parameters. Which would look something like this:
String sql = "select * from orders where date_purchased < #DatePurchased";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.Add("DatePurchased", MySqlType.DateTime).Value = varDate;
adapter.Fill(dataSet);
Using parameters will ensure the values are converted and will also prevent SQL Injections
Try something like where DBdatetime < "'" + vardate + "'"
One word of caution, check the formats of the two dates. I had a problem in a previous app where the DB had seconds and milliseconds, whereas the app provided just a data and set the time to 00:00. This resulted in records for the current date not showing in the result set. Thus, I had to add 23:59 to the date to get all the records for the current day.
You can retrieve the values between the two data using the following MySQL Query
SELECT * FROM table_name WHERE dbvalue < varData

Categories