根据其他列信息更新sqlite列

时间:2019-05-31 16:03:24

标签: python-3.x sqlite

我正在尝试使用来自sqlite数据库的信息,并使用Python 3.6在某些条件下更新其他列

python 3.6和sqlite

def open_days(signed_date,completed_date):
    fmt = '%Y-%m-%d'
    if completed_date == '':
        if signed_date:
            sdate = datetime.strptime(signed_date, fmt)
            tdate = datetime.now() 
            delta = str((tdate - sdate).days)

            return delta

    else:
        sdate = datetime.strptime(signed_date, fmt)
        cdate = datetime.strptime(completed_date, fmt)   
        delta = str((cdate - sdate).days)

        return delta

conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute("SELECT * FROM data_table")
for row in cur:
    cur.execute("UPDATE data_table SET days_open=? WHERE numid=?", (open_days(row[1],row[2]),row[0]))
    cur.fetchall()

cur.close()
conn.commit()

我希望结果是:

numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,32
3456,2019-04-29,2019-05-13,14
4567,,,None

如果天数是手动设置的,则该值未使用正确的值

numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,16
3456,2019-04-29,2019-05-13,16
4567,,,16

请注意,按照示例显示昏迷之间有一些空白,这可能是没有签名日期和完成日期尚未注册到数据库中。

如果注册了签署日期和完成日期,则天数是完成日期和签署日期之间的差额

如果仅注册签名日期,则天数是今天的日期和签名日期之间的差额

如果没有签名日期,则天数为无

1 个答案:

答案 0 :(得分:0)

我找到了一种更新行的方法:

conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()

for row in cur.execute('SELECT signed_date, completed_date, open_days(signed_date,completed_date) FROM data_table'):
    cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()

根据Sam输入更改为:

conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()
cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()