PostgreSQL: 42883 Operator does not exist: timestamp without time zone = text - c#

I am using Npgsql 3.0.3.0 and PetaPoco latest version.
When I run this command:
var dateCreated = DateTime.Now; // just an example
var sql = new Sql("WHERE date_created = #0", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
var category = db.SingleOrDefault<Category>(sql);
I get the following error:
Npgsql.NpgsqlException 42883: operator does not exist: timestamp
without time zone = text
I understand the error message is saying I'm trying to compare a timestamp (date) with a text, however for me it's perfectly valid to compare them as I am expecting the following SQL statement to be built:
SELECT * FROM category WHERE date_created = '2017-02-03 15:00:00'
I don't really want to typecast my database column to text for performance reasons.

You need to cast value to timestsamp:
var sql = new Sql("WHERE date_created = #0::timestamp", dateCreated.ToString("yyyy-MM-dd HH:00:00"));

You need to explicit typecast text to timestamp.
Try using :
TO_TIMESTAMP(date_string,'YYYY-MM-DD')

As #roman-tkachuk answered, you can tell PostgreSQL to cast your string into a timestamp.
Or better yet, you can simply send a timestamp to PostgreSQL directly, rather than sending a string representation of a timestamp and having it cast. To do that, simply send dateCreated directly, without the ToString().

Related

Convert SQLite timestamp to DateTime in C#

I am trying to assign a property of an object the value of a column containing a timestamp in SQLite. Currently the property is of type DateTime, but I've tried string type with no change. I've tried using Convert.ToDateTime(rdr.GetString(5).ToString()) with no change.
Here's the exception I get:
System.InvalidCastException: Specified cast is not valid.
at System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
at System.Data.SQLite.SQLiteDataReader.GetDateTime(Int32 i)
at ConsoleHelpTicket.Data.FillQueue(SQLiteConnection conn, Queue`1 queue) in E:\...\Data.cs:line 142
Here's the property declaration:
public DateTime OpenDate { get; set; }
Here's the method where I try the assignment:
public static void FillQueue(SQLiteConnection conn, Queue<Ticket> queue)
{
try
{
var cmd = new SQLiteCommand($"select * from Tickets order by OpenDate desc;", conn);
using SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Ticket ticket = new Ticket();
ticket.Tid = rdr.GetInt32(0);
ticket.Title = rdr.GetString(2);
ticket.Description = rdr.GetString(3);
ticket.OpenDate = rdr.GetString(5); <---------- PROBLEM LINE
ticket.ClosedDate = rdr.GetString(6);
ticket.Open = rdr.GetBoolean(7);
ticket.Location = rdr.GetString(8);
System.Console.WriteLine($"Added TID: {rdr.GetInt32(0)} Title: {rdr.GetString(2)} to queue.");
queue.Enqueue(ticket);
}
}
So I figured out the problem(s).
I was using SQLite's TIMESTAMP as the default column value, and I was allowing that to be set for the column value on every insert. I edited C# insert line to insert DateTime.Now. Yes SQLite supports TimeStamp as a data type, but the documentation says it's really stored as a string. See the documentation
After much troubleshooting I realized I got my column numbers mixed up and I was trying to import parse a bool as time, which obviously will throw an exception. I'm rewriting my code now to be more dynamic to avoid this type of problem in the future.
Finally I ended up using this line ticket.OpenDate = DateTime.Parse(rdr.GetString(6)); to successfully assign the column value to a DateTime property. My thinking is that if SQLite is storing it as a string, I should retrieve it as a string and parse it to DateTime. I'm also storing the value as a native DateTime value from C# instead of relying on the TimeStamp value from SQLite. I haven't tested to see if I can parse a TimeStamp value though.

How to truncate time part from date in linq query?

Hi I am trying to write linq query to get some details from Sql table. I have created column and storing date and time both. while returning i want to ommit time part. May I know is this possible?
List<returnObject> obj = new List<returnObject>();
obj = (from c in objectDB.NCT_Project
join user in objectDB.NCT_UserRegistration on c.adminUserId equals user.User_Id
where c.adminUserId == userId
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate //currently returns datetime
}).ToList();
Any help would be appreciated. Thank you.
Use DbFunctions.TruncateTime method:
created = DbFunctions.TruncateTime(c.createdDate)
According to the docs:
When used as part of a LINQ to Entities query, this method invokes the
canonical TruncateTime EDM function to return the given date with the
time portion cleared.
All you need to do is call 'Date' property on createdDate.
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate.Date
}).ToList();
you can try this one.
created = c.createdDate.ToString("HH:mm")
created = c.createdDate.ToString("H:mm")
created = c.createdDate.ToString("hh:mm tt")
created = c.createdDate.ToString("h:mm tt")
also see this question : How to get only time from date-time C#
If you can get date comparison out of the LINQ and leave the rest there, you can use this syntax:
sqlite.Query<Entity>("date comparison").Where("other queries")
The predicate I used in the Query() function had to return only todays orders and looked something like this:
select * from Order where date(orderDate/ 10000000 - 62135596800, 'unixepoch') = date('now')

DateTime is saved incorrectly into my database

I'm struggling as why my DateTime is saved incorrectly into my database.
I pass it the value 20/12/2015 (as a string) alongside the format (dd/MM/yyyy) and parse it into a DateTime but it always saves into my SQL Server database as 06/12/2015
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
projectPlan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null); //ShortDateTime is 20/12/2015, DateFormat is dd/MM/yyyy
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan = projectPlan;
this._dc.SaveChanges();
}
Erm, didn't you mean updating the StartDate property of your entity and then saving it back into the database:
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null);
this._dc.SaveChanges();
}
On this line you are basically killing every context EF knows about:
plan = projectPlan;
So if you looked at the actual SQL query generated against your SQL database you would have noticed that exactly 0 rows were updated.
The textual representation is not stored in the server, neither is it in .NET when you have a DateTime object. It is just a large number counting the number of "ticks" from a set time.
You will need to format the date when you select the date out back in to a string, the inserting side can't control it (unless the inserting side also stores the formatting string or you don't store it as a date and instead store it as a string)

Problems with Data type in Npgsql query

I'm trying to insert a row in a PostgreSQL table with a date column. On the UI, I got a DateTimePicker where the user selectes the proper date. So far I got this:
On the UI:
objPresupuesto.date = this.dtpFechaPres.Value.ToString("yyyy-MM-dd");
On the method who inserts the row:
NpgsqlCommand query = new NpgsqlCommand("insert into presupuesto(presupuesto, codigo, descripcion, fecha, cliente, proyecto, total) values(nextval('presupuesto_presupuesto_seq'), #codigo, #descripcion, #fecha, #cliente, #proyecto, #total);Select lastval();", conn);
...
query.Parameters.Add(new NpgsqlParameter("fecha", NpgsqlDbType.Date, 0, "fecha"));
...
query.Parameters[2].Value = obj.date.toString;//without the toString it also fails
It throws this exception:
Specified cast is not valid.
The obj.date value is 2011-04-29. tryied putting single quotes around, but It also fails.
The database column type is date.
Anyone has done this before? Any ideas?
I checked this link searching for and aswer but it doesn't helped.
Thanks
The first thing I noticed is that when you are adding your parameter it is missing the "#" from the beginning where your command references the value with the "#".
Are you sure that the Parameters[2] is your "fecha" parameter?
try use:
npgsqlCommand.Parameters.Add("fecha", NpgsqlDbType.Date).Value = DateTime.Now;
For more readable code.
Type of obj.date is DateTime struct?
Add to connection string parameter Convert Infinity DateTime
For more info check: http://www.npgsql.org/doc/connection-string-parameters.html
query.Parameters[2].Value = CDate(obj.date)

How to convert the date from the DateTimePicker control into the mm/dd/yy 12:54:30 PM format (Current date time format)?

I am developing mobile application in C#. I am using the SQLite database to store the data. In the SQLite database I am storing the information related to the customer. In that I am storing the date with mm/dd/yy 12:54:30 PM format. Now I want to retrive the customer data based on start date & end date. I am using the following code
ShowRegistrationKeyDetails ShowRegKeyDetailsObj = new ShowRegistrationKeyDetails();
// set properties
ShowRegKeyDetailsObj.FromDate = FromdateTimePicker.Value.ToString();
ShowRegKeyDetailsObj.ToDate = TodateTimePicker.Value.ToString();
When I fire the SQL Queries based on these values I am not getting the proper result. I need to convert the above values of FromdateTimePicker.Text & TodateTimePicker.Text into the mm/dd/yy 12:54:30 PM format.
I am using the following code
public SQLiteDataReader getClient_And_RegistrationKeys(int Customer_ID, String FromDt, String ToDt)
{
SQLiteDataReader SQLLiteDrObj = null;
DataManager myDatabase = new DataManager("CompNet.db");
myDatabase.Init(false);
string[] Parameter = new string[] { "#Val_Customer_ID", "#Val_FromDt", "#Val_ToDt" };
Object[] Objval = new Object[] { Customer_ID, FromDt, ToDt };
string sqlCommandText = "Select Activation_Date, Standard_ID, Client_Key, Registration_Key from Activation_Details where Customer_ID=#Val_Customer_ID And Activation_Date between #Val_FromDt And #Val_ToDt";
SQLLiteDrObj = myDatabase.ExecuteReader(sqlCommandText, Parameter, Objval);
return SQLLiteDrObj;
}
I have tried this code. Now I am getting the date in the format in which I want but I am not getting the required rows as output. There is no row in the output. Where I am going wrong ? Can you please provide me any code?
Don't use Text to start with - use DateTimePicker.Value to get the value as a DateTime.
Ideally, then don't convert it into text when using SQLite either - use a parameterized query instead of formatting it at all. See this article as one example of using parameterized queries from C# with SQLite.
As a general rule, try to avoid going through text wherever possible. It's great for displaying values to users, but lousy for being confident that you've got the right data without having to be careful about different formats etc.

Categories