Odbc Paradox Driver WHERE clause Date - c#

I am using an Odbc driver with Paradox. I have a table with a date in it. I am trying to query by the date in that column. I can't seem to get the where clause to work. I can get the record searching by ints, but I don't know how to use the date time.
OdbcCommand comm= new OdbcCommand("SELECT * FROM [Journal] WHERE" +
"[Date] = 04/02/2009 ",
new OdbcConnection(#"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=d:\\ics\\tables\\HISTORY;Dbq=d:\\ics\\tables\\HISTORY;CollatingSequence=ASCII"));
OdbcDataAdapter adapt = new OdbcDataAdapter(comm);
DataTable table = new DataTable();
adapt.Fill(table );

Ok I figured it out.
...where [Date] = {d 'yyyy-MM-dd'} AND...
In odbc you have to use the {} to define an object, and the d defines the format of the date.
You can use the following.
{d 'value'} yyyy-mm-dd
{t 'value'} hh:mm:ss
{ts 'value'} yyyy-mm-dd hh:mm:ss

Look for Date/Time functions in Paradox that will convert a string to a date. It is very tricky to use a String as a date like in your SQL. There must be some functions like TO_DATE or similar that will properly format it for you.

Related

How to pass date time format in dapper parameter for postgresSQL?

For a query on a table in PostgreSQL I am able to fetch data correctly.
var query = "Select Id,name from employee
where
joiningTime BETWEEN '{startDateTime:yyyy-MM-dd HH:mm:ss}' AND '{endDateTime:yyyy-MM-dd HH:mm:ss}'"
The data are returned correctly but since this approach is prone for SQL Injection, I want to change this to parameterized way
var query = "Select Id,name from employee
where
joiningTime BETWEEN '#startDateTime' AND '#endDateTime'"
var result = dbConnection.Query<Result>(query, new {startDateTime, endDateTime });
How can the format be passed still with parameters?
DateTimes don't have a format, they're like number (eg like 1000 can be formatted as 1000.0 or 1x10^3 etc but it's still just a thousand).
You just write the query like:
SELECT * FROM t WHERE dateCol BETWEEN #fromDate AND #toDate
Note: you don't put ' around parameter names!
And in the dapper call you put datetime typed parameters:
DateTime x = DateTime.Now.AddDays(-1);
DateTime y = DateTime.Now;
dbConnection.Query<Result>(query, new { fromDate = x, toDate = y});
If, in your database, you've made your datetime columns varchar and filled them with strings that's the first thing you should fix (make them a proper date type)..
But even if you did dothis, the advice wouldn't change:
DateTime x = DateTime.Now.AddDays(-1);
DateTime y = DateTime.Now;
dbConnection.Query<Result>(
"SELECT * FROM t WHERE dateCol BETWEEN #fromDate AND #toDate",
new {
fromDate = x.ToString("yyyy-MM-dd HH:mm:ss"),
toDate = y.ToString("yyyy-MM-dd HH:mm:ss")
}
);
You're still writing parametyers into your SQL, you're now putting formatted strings into the parameter values to match the formatted strings in the DB table. Don't do this if your table holds DATE/TIME/TIMESTAMP type columns - this is only for if you've arrange the questionable(foolish)_ situation of storing your dates as strings and are unwilling to change it (you should)

How to add parameters in a SQL select query?

How to add parameters in a SQL select query?
string time = 2013-09-25 00:00:00;
I wish to use the time variable in the below mentioned SQL query
Select LastUpdated from Employee where LastUpdated > time;
Try this:
string sqlDate = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
It appears what the OP is asking is how to convert a VARCHAR to a DATETIME in SQL Server not actually a String to DateTime in C#.
You will need to use the following to convert to a DATETIME:
SELECT LastUpdated
FROM Employee
WHERE LastUpdated > CONVERT(datetime, varTime, 121);
See the following MS Reference for more information.
To echo others though, you should just pass the parameter in as a datetime and let the database provider factory handle the conversion of appropriate types, or add a new method that actually returns a DateTime. In the future, I wouldn't name a method GetUpdateTime unless it actually returns a type of Time.
You can convert your string in C# code to DateTime using
DateTime.TryParse() or Convert.ToDateTime()
OR
Convert VARCHAR to DATETIME in SQL using
Convert(datetime, time)
I just framed my question in a wrong, the query remains the same though. I just wanted time to be added as a paramter in my SQL-query. The code for the same looks like
String commandText = "Select LastUpdated from Employee where LastUpdated > :time;";
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(commandText, connection);
command.Parameters.Add("time", time);
Thanks a lot for your help!
My bad that I couldn't frame the question properly.

Compare datetime column with datetime variable in asp.net sql where clause

I have a column named compare_time(datatype: DateTime) in database. Its value is inserted as 3/8/2017 12:09:08 AM. Now in c# I want to write a query to compare if this column value is equal to Singapore's current date time.(Only need to compare the date.). Current Singapore date time is get as 08-03-2017 PM 03:35:11.
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM time_details where compare_time='"+dt+"' ", con1);
Please help to correct the where clause.
The first step is to not compare the dates using automatic string conversion but use a parameter.
Still this is not enough because your DateTime variable contains also the time part as well the database column. So you need to isolate the date part both on the database data and in the variable
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter(#"SELECT * FROM time_details
where Convert('Date',compare_time) = #date", con1);
adapter.SelectCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dt.Date;
....
In this way you don't let the compiler decide which is the right string 'format' that is correct for Sql Server to understand your query.
Instead you pass the DateTime variable as a Date (using the Today property which doesn't have a meaningful time part) to the database engine that now has all the info to make the correct comparison.
Notice that this approach could not be the most efficient one. That CONVERT inside the WHERE clause could wreak havoc with your indexes. Probably you could use a different approach
string cmdText = #"SELECT * FROM time_details
where compare_time >= #init AND
compare_time < #end";
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, con1);
adapter.SelectCommand.Parameters.Add("#init", SqlDbType.DateTime).Value = dt.Date;
adapter.SelectCommand.Parameters.Add("#end", SqlDbType.DateTime).Value = dt.Date.AddDays(1);

SQLite - no data sqlite select with condition on datetime

I have select query in SQLite Database. There is a LogInTime field that datatime datatype.
Here is AccessDate variable passing date "11/16/2016" like format
string sql = "SELECT * FROM Tble_Login where LogInTime = '" + AccessDate + "'";
The SQLite Tble_Login looking like this,
After excute this query, no data? How can I get data?
Referring to the SQLite documentaion you should use following format for AccessDate
YYYY-MM-DDor YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS. On the documentation page you can find more formats in the section Time Strings
You can also try to use the BETWEEN statement like in this question
string sql = #"SELECT * FROM Tble_Login where LogInTime BETWEEN ""2016-11-16"" AND ""2016-11-17""";

Passing C# datetime value to Oracle DB Query

I have a SQL query that I am passing a C# variable into my Oracle DB.
I am having trouble passing a C# datetime variable, "PROCESS_DATE", into my query in my application. I do not get any records back. If I copy the query into my oracle developer tool, TOAD, it works fine and I get multiple records.
Here is the query I am using in my application:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE";
I also tried converting the datetime variable into a shortDateString() so it matches the database exactly I then used the TO_DATE function, which I have to use if I query dates directly in TOAD, without any luck. The shortDateString() changes my date into: 1/16/2016, which is what I need, but the OracleDataReader does not like it. Here it the query with the TO_DATE function:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = TO_DATE(:pPROCESS_DATE, 'MM-DD-YYYY'";
:pROCESS_DATE is a datetime variable that is passed in.
There must be a breakdown between C# and Oracle in relation to handling a datetime variable. I am using Oracle DataReader to handle the processing of the query.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
If I use the TO_DATE function, the application will not step into the while loop. If I use the original query, it does but returns no data.
The datetime variable PROCESSDATE looks like this:
1/16/2016 12:00:00 AM
I notice it has a timestamp on it, so I'm not sure if that is the problem or not.
The data in Oracle is like this:
1/16/2016
Unless I've totally misunderstood your issue, I think you might be making this harder than it needs to be. ODP.net handles all of that dirty work for you. If PROCESS_DATE is an actual DATE datatype in Oracle, then you just need to pass an actual C# DateTime variable to it and let ODP.net do the heavy lifting. There is no need to do conversion of any type, provided you are passing an actual date:
DateTime testDate = new DateTime(2015, 7, 16);
OracleCommand cmd = new OracleCommand(
"SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE",
conn);
cmd.Parameters.Add(new OracleParameter("pPROCESS_DATE", OracleDbType.Date));
cmd.Parameters[0].Value = testDate;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
object o = reader.IsDBNull(0) ? null : reader.GetValue(0);
}
reader.Close();
If your data in C# is not a date, I'd recommend making it one before even trying:
DateTime testDate;
if (DateTime.TryParse(testDateString, out testDate))
{
// run your query
}
As per my comment, please try below and see this resolves.
TRUNC(TO_DATE(:pPROCESS_DATE,'MM-DD-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 1/16/2016 12:00:00 AM.
TRUNC(TO_DATE(:pPROCESS_DATE,'DD-MM-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 16/1/2016 12:00:00 AM.
First, I learned that my code will not go into the code below unless I actually have records returned to me.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
Second, to get ProcessDate to work, I needed to take the string that was coming from my View, convert it to a datetime, and then I formatted it back as a string. It may not be best practices but it worked.
public JsonResult GetGroupReportData ( String reportDate )
{
DateTime processDate = DateTime.Parse ( reportDate );
var monthlyReport = SelectAllGroupRprt (processDate.ToString("MM/dd/yyyy");
return new JsonResult ( )
{
Data = monthly,
MaxJsonLength = Int32.MaxValue
};
}

Categories

Resources