简体   繁体   English

SQLite 查询无法正常工作

[英]SQLite query not functioning properly

I have made every attempt that I know of to make this work, but at this point I think I am just running in circles.我已经尽我所能来完成这项工作,但在这一点上,我认为我只是在兜圈子。

I am taking user input and using that to query a database.我正在接受用户输入并使用它来查询数据库。 The caveat is that there are dates within the database that need to have days added to them, and to make sure that the user is seeing all the UPDATED information between the dates they chose, I changed the user's start date so that it includes two months beforehand.需要注意的是,数据库中的某些日期需要添加天数,为了确保用户在他们选择的日期之间看到所有更新的信息,我更改了用户的开始日期,使其包括两个月预先。

At this point, the information is passed into a dataframe where it is then filtered to contain only relevant information as well as adjusting the dates that need to be adjusted.此时,信息被传递到 dataframe 中,然后过滤以仅包含相关信息以及调整需要调整的日期。 After that, it's passed through a mask on the dataframe to make sure that the user is seeing the updated information only, and not dates that are outside of their chosen range that originally weren't.之后,它通过 dataframe 上的掩码传递,以确保用户只看到更新的信息,而不是超出他们选择的范围而最初没有看到的日期。

There were a few points throughout this process that my code was running properly, but I kept realizing there were changes that needed to be made.在整个过程中,有几点表明我的代码运行正常,但我一直意识到需要进行一些更改。 As to be expected, those changes caused my code to break and I've not been able to figure out how to fix it.正如所料,这些更改导致我的代码中断,我无法弄清楚如何修复它。

One issue is that the SQL queries are not returning the correct information.一个问题是 SQL 查询没有返回正确的信息。 It seems that the chosen start date will allow any entries past that date, but the chosen end date will only include database entries if the end date is very near to the highest date in the database.似乎所选的开始日期将允许该日期之后的任何条目,但如果结束日期非常接近数据库中的最高日期,则所选的结束日期将仅包括数据库条目。 The problem with that is that the user may not always know what the highest value in the database is, therefore they need to be able to choose an arbitrary value to query by.这样做的问题是用户可能并不总是知道数据库中的最高值是什么,因此他们需要能够选择任意值进行查询。

There is an also an issue where it seems the query only wants to work some of the time.还有一个问题,查询似乎只希望在某些时候工作。 On two separate instances I ran the same exact queries and it only worked one time and not the other.在两个单独的实例上,我运行了相同的确切查询,它只工作了一次,而另一次则不行。

Here is my code:这是我的代码:

 self.StartDate = (self.StartMonth.get() + " " + self.StartDay.get() + "," + " " + self.StartYear.get())
    self.StartDate = datetime.strptime(self.StartDate, '%b %d, %Y').date()
    self.StartDate = self.StartDate - timedelta(days = 60)
    self.StartDate = self.StartDate.strftime('%b %d, %Y')

    self.EndDate = (self.EndMonth.get() + " " + self.EndDay.get() + "," + " " + self.EndYear.get())
    self.EndDate = datetime.strptime(self.EndDate, '%b %d, %Y').date()
    self.EndDate = self.EndDate.strftime('%b %d, %Y')

    JobType = self.JobType.get()

    if JobType == 'All':
        self.cursor.execute('''
                            SELECT
                                *
                            FROM
                                MainTable
                            WHERE
                                ETADate >= ? and
                                ETADate <= ?
                            ''',
                            (self.StartDate, self.EndDate,)
                            )
        self.data = self.cursor.fetchall()
    else:
        self.cursor.execute('''
                            SELECT
                                *
                            FROM
                                MainTable
                            WHERE
                                ETADate BETWEEN
                                    ? AND ?
                                AND EndUse = ?
                            ''',
                            (self.StartDate, self.EndDate, JobType,)
                            )
        self.data = self.cursor.fetchall()

    self.Data_Cleanup()
    
def Data_Cleanup(self):

    self.df = pd.DataFrame  (
                            self.data, 
                            columns =   [
                                        'id',
                                        'JobNumber',
                                        'ETADate',
                                        'Balance',
                                        'EndUse',
                                        'PayType'
                                        ]
                            )

    remove = ['id', 'JobNumber']
    self.df = self.df.drop(columns = remove)
    self.df['ETADate'] = pd.to_datetime(self.df['ETADate'])
    self.df.loc[self.df['PayType'] == '14 Days', 'ETADate'] = self.df['ETADate'] + timedelta(days = 14)
    self.df.loc[self.df['PayType'] == '30 Days', 'ETADate'] = self.df['ETADate'] + timedelta(days = 30)

    self.df['ETADate'] = self.df['ETADate'].astype('category')
    self.df['EndUse'] = self.df['EndUse'].astype('category')
    self.df['PayType'] = self.df['PayType'].astype('category')


    mask = (self.df['ETADate'] >= self.StartDate) & (self.df['ETADate'] <= self.EndDate)
    print(self.df.loc[mask])

Ideally, the data would be updated before it is added to the database, but unfortunately the source of this data isn't capable of updating it correctly.理想情况下,数据将在添加到数据库之前进行更新,但不幸的是,此数据的来源无法正确更新它。

I appreciate any help.我很感激任何帮助。

You are storing dates as a string, formatted like Jan 02, 2021 .您将日期存储为字符串,格式为Jan 02, 2021 That means you'll compare the month first, alphabetically, then the day numerically, then the year.这意味着您将首先按字母顺序比较月份,然后按数字比较日期,然后是年份。 Or, to take a few random dates, the sort order looks like this:或者,取几个随机日期,排序顺序如下所示:

Dec 23, 2021
Jan 01, 2021
Nov 07, 2026
Nov 16, 2025

If you want a query that makes sense, you'll either need quite a bit of SQL logic to parse these dates on the SQLite side, or preferably, just store the dates using a format that sorts correctly as a string.如果您想要一个有意义的查询,您需要相当多的 SQL 逻辑来解析 SQLite 端的这些日期,或者最好只使用正确排序为字符串的格式存储日期。 If you use .strftime("%Y-%m-%d") those same dates will sort in order:如果您使用.strftime("%Y-%m-%d")这些相同的日期将按顺序排序:

2021-01-01
2021-12-23
2025-11-16
2026-11-07

This will require changing the format of the columns in your database, of course.当然,这将需要更改数据库中列的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM