QDateTime with sqlite3 - c++

I'm using Sqlite3 with Qt , anyway to save the DateTime form in the db i used Text type , see this from my db :
data
so the INSERT and SELECT is work very , but how i could make specific SELECT !
my code :
QString("SELECT * from main.sell_cash_log WHERE 'when' >= '%1' AND 'when' <= '%2'").arg(ui->fromdate->dateTime().toString("dd-MM-yyyy:HH-mm-ss")).arg(ui->todate->dateTime().toString("dd-MM-yyyy:HH-mm-ss"))

You're probably better off using one of the date operaterators to get info for a specific date
https://www.tutorialspoint.com/sqlite/sqlite_data_types.htm
To select all in the month of November:
SELECT * FROM main.sell_cash_log WHERE strftime('%Y-%m-%d', when) BETWEEN "11-01-2016" AND "11-31-2016"
See also SQL Select between dates which is where I copied that query q

The problem was by the field called when , in insert query i was useing escape string ('when') but with select not work (' ' ) so i used (when) and it's workd :
:
CartItems->setQuery(QString("SELECT * from main.sell_cash_log WHERE datetime(`when`) BETWEEN datetime('%1') AND datetime('%2')").arg(ui->fromdate->dateTime().toString("yyyy-MM-dd hh:mm:ss")).arg(ui->todate->dateTime().toString("yyyy-MM-dd hh:mm:ss")));

Related

Add field value to datefield in django

Parent Model:
id = auto_generated
add_me = IntegerField()
Child Model:
id = ForeignKey(Parent)
my_date= DateTime(auto_now_add=True)
and,
today = django.util.timezone.now()
time = today - timedelta(days=10)
now I want to retrieve records as:
child.objects.filter(my_date__lte= time +
(timedelta(days=1)*F('id__add_me')))
Everthing works fine except:
(timedelta(days=1)*F('id__add_me'))
I am using MYSQL:
I get:
django.db.utils.ProgrammingError:
(1064, "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
'* `parent`.`add_me`))))' at line 1")
Query Generated is like:
SELECT* FROM `child INNER JOIN `parent` ON
(`child`.`id` = `parent`.`id`) WHERE
( `child`.`my_date` <= ((2018-07-30 09:11:18.670900
+ (INTERVAL '86400.000000' SECOND_MICROSECOND * `parent`.`add_me`))))
As you can see * (multiplication) is with INTERVAL. I hard coded query putting the parent.add_me inside the INTERVAL and got it right, how can I do so via Django? i.e. DATE_ADD in django
I want to reduce days from a datetime field, where days are stored in master table field.
Maybe it doesn't work with MYSQL, so please provide an alternative solution to such.
UPDATED:
Somehow I found error by writing MYSQL query as:
SELECT * FROM child INNER JOIN parent ON" \
child.id = parent.id WHERE
child.my_date<= '" + str(time) + \
"' + INTERVAL parent.add_me DAY "
The problem was with single quotes (') i.e. in mysql for <= the datetime shall be within single quotes else won't work. i.e.
2018-07-30 09:11:18.670900 shall be written as
'2018-07-30 09:11:18.670900' if adding with INTERVAL,
But as queries are generated by Django, how do I achieve that?

Django queryset on related field

Django is to making a query much more complicated than it needs to be.
A Sentiment may have a User and a Card, and I am getting the Cards which are not in the passed User's Sentiments
This is the query:
Card.objects.all().exclude(sentiments__in=user.sentiments.all())
this is what Django runs:
SELECT * FROM "cards_card"
WHERE NOT ("cards_card"."id" IN (
SELECT V1."card_id" AS "card_id"
FROM "sentiments_sentiment" V1
WHERE V1."id" IN (
SELECT U0."id"
FROM "sentiments_sentiment" U0
WHERE U0."user_id" = 1
)
)
)
This is a version I came up with which didn't do an N-Times full table scan:
Card.objects.raw('
SELECT DISTINCT "id"
FROM "cards_card"
WHERE NOT "id" IN (
SELECT "card_id"
FROM "sentiments_sentiment"
WHERE "user_id" = ' + user_id + '
)
)')
I don't know why Django has to do it with the N-Times scan. I've been scouring the web for answers, but nothing so far. Any suggestions on how to keep the performance but not have to fall back to raw SQL?
A better way of writing this query without the subqueries would be:
Card.objects.all().exclude(sentiments__user__id=user.id)

Convert varchar to double fails when I use ADO yet it works in MS Access

I have made a query that ran successfully in the first version of my program, using ADO and C++ to query MS Access 2007 database.
However, the structure of my database had to be modified.
Fields that were once of type double are now varchar.
When I execute the same query on the modified database, it reports data type mismatch, as it should.
EDITED QUERY TO HELP THE POSTER OF THE FIRST SOLUTION:
Here is simplified version of my query:
wchar_t query = L" select ( ads(Field) + Field ) / 2 from MyTable where PrimaryKey = 1;";
Field was of type double, but now is varchar.
I have tried using CDbl like this:
wchar_t query = L" select ( abs( CDbl(Field) ) + CDbl(Field) ) / 2 from MyTable where PrimaryKey = 1;";
It works when I create query in MS Access, but in my program I still get data type mismatch error reported.
I have tried to find alternative on the Internet, and have thought that CAST or CONVERT can sole this, but it seems that they do not work in MS Access.
Is there any solution for this ?
Thank you.
Regards.
Have you tried to convert the value to Double not in the query but after the query has been run?
CAST and CONVERT are not Access SQL functions
I dont use c++ but even with a small subroutine in Access using the ADO object I cannot reproduce the error...
Sub test()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim db As ADODB.Connection
Set db = CurrentProject.Connection
rs.Open "SELECT (Abs(CDbl(Field))+CDbl(Field))/2 AS A FROM MyTable;", db
While rs.EOF = False
Debug.Print rs!A
rs.MoveNext
Wend
End Sub

JPA Criteria Builder

Currently , I am doing some JPA stuff, but having some problem, as described below :
Table Structure-
Id(Integer) , StatusType(String) , CreationTime(TimeStamp)
I want to extract StatusType , Count(StatusType) and CreationTime[GROUP BY](Cast in Date instead of TimeStamp)
if CreationTime is grouped in TimeStamp then no grouping is done because of uniqueness of the timestamp
I have a sql query that solves my purpose - Select StatusType , Count(*) , Date(CreationTime) from Table Group By Date(CreationTime)
It casts Timestamp to Date & group by CreationTime,
but I want this to be with CriteriaBuilder API or at least in JPQL Query , so that it works for all Database. Any idea about it?
Thanks in advance.
you may cast the timestamp to a integer with "yyyyMMdd" format, by using:
year(CreateTime) * 10000 + month(CreateTime) * 100 + day(CreateTime)
Yes, timeStamp can be casted to Date using JPQL.
I think this blog post will solve your problem.

Doctrine 2 edit DQL in entity

I have several database tables with 2 primary keys, id and date. I do not update the records but instead insert a new record with the updated information. This new record has the same id and the date field is NOW(). I will use a product table to explain my question.
I want to be able to request the product details at a specific date. I therefore use the following subquery in DQL, which works fine:
WHERE p.date = (
SELECT MAX(pp.date)
FROM Entity\Product pp
WHERE pp.id = p.id
AND pp.date < :date
)
This product table has some referenced tables, like category. This category table has the same id and date primary key combination. I want to be able to request the product details and the category details at a specific date. I therefore expanded the DQL as shown above to the following, which also works fine:
JOIN p.category c
WHERE p.date = (
SELECT MAX(pp.date)
FROM Entity\Product pp
WHERE pp.id = p.id
AND pp.date < :date
)
AND c.date = (
SELECT MAX(cc.date)
FROM Entity\ProductCategory cc
WHERE cc.id = c.id
AND cc.date < :date
)
However, as you can see, if I have multiple referenced tables I will have to copy the same piece of DQL. I want to somehow add these subqueries to the entities so that every time an entity is called it adds this subquery.
I have thought of adding this in a __construct($date) or some kind of setUp($date) method, but I'm kind of stuck here. Also, would it help to add #Id to Entity\Product::date?
I hope someone can help me. I do not expect a complete solution, one step in a good direction would be very much appreciated.
I think I've found my solution. The trick was (first, to update to Doctrine 2.2 and) using a filter:
namespace Filter;
use Doctrine\ORM\Mapping\ClassMetaData,
Doctrine\ORM\Query\Filter\SQLFilter;
class VersionFilter extends SQLFilter {
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) {
$return = $targetTableAlias . '.date = (
SELECT MAX(sub.date)
FROM ' . $targetEntity->table['name'] . ' sub
WHERE sub.id = ' . $targetTableAlias . '.id
AND sub.date < ' . $this->getParameter('date') . '
)';
return $return;
}
}
Add the filter to the configuration:
$configuration->addFilter("version", Filter\VersionFilter");
And enable it in my repository:
$this->_em->getFilters()->enable("version")->setParameter('date', $date);