首页 > 解决方案 > 使用python将2个日期值插入sqlite db中的列

问题描述

在 python 中使用 sqlite 的新手。我正在尝试通过 Python 将两个日期值插入到 sqlite db 中的两个日期列中。

import sqlite3

def create_connection(db_file):
    # Create a database connection to a SQLite database
    # Param: db_file as str. Return: connection objects or None
    try:
        conn = sqlite3.connect(db_file)
        cur = conn.cursor()
        return conn, cur
    except Error as e:
        print (e)
        return None

my_conn, my_cur = create_connection(dpd_sqlite_db_dir)

def create_sqlite_table_if_nonexist(conn, table_name):
    sql = 'create table if not exists '+table_name+' (data_download_date datetime, script_executed_date datetime)'
    conn.execute(sql)

create_sqlite_table_if_nonexist(my_conn, 'df_timestamp_en')

def insert_timestamp(conn, timestamp):
    # execute insert into db
    sql = ''' INSERT INTO df_timestamp_en (data_download_date, script_executed_date) VALUES(?,?) '''
    cur = conn.cursor()
    cur.execute(sql, timestamp)
    return cur

timestamp_info = ('2018-10-30', '2018-11-30')
insert_timestamp(my_conn, timestamp_info)

它运行并创建了包含两个日期列的表,但它不插入timestamp_info的值。

标签: python-3.xsqlite

解决方案


推荐阅读