首页 > 解决方案 > 在 Python 中定义一个函数以将日期插入到 SQLite 表中?

问题描述

所以我对编程世界很陌生,我已经了解了 python 的基础知识,并且正在继续尝试使用 python 和 sqlite 来制作一个小程序。

我已经阅读了 SQLite 文档,并且了解如何插入和调用数据,但是对于多次执行此操作,似乎使用函数来完成此操作在逻辑上是答案,这就是我遇到障碍的地方。

到目前为止,这是我根据自己尝试将代码转换为函数的直觉得出的结论:

i_date = input('Input Date as YYYY-MM-DD > ')
i_trans = input('Select Buy or Sell >')
i_symbol = input('Input Stock Ticker > ')
i_qty = input('Input Qty to be Purchased > ')
i_price = input('Input Buy/Sell Price > ')

update_tbl = ('i_date' + 'i_trans' + 'i_symbol' + 'i_qty' + 'i_price')


def update_table(date, trans, symbol, qty, price):
    c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', update_tbl)

update_table(update_tbl)

结果是它肯定似乎将日期传递给函数,但只是第一项。它产生的错误是:

Traceback (most recent call last):
  File "SQL.py", line 25, in <module>
    update_table(update_tbl)
TypeError: update_table() missing 4 required positional arguments: 'trans', 'symbol', 'qty', 
and 'price'

我不确定错误是否在于我如何将所有变量作为单个变量添加到 update_tbl,或者错误在于我如何将其传递给函数。我最初尝试用逗号分隔每个变量,并返回相同的结果。

谁能指出我正确的方向?

编辑:到目前为止,这是我成功将参数传递给函数的唯一方法:

i_date = input('Input Date as YYYY-MM-DD > ')
i_trans = input('Select Buy or Sell > ')
i_symbol = input('Input Stock Ticker > ')
i_qty = input('Input Qty to be Purchased > ')
i_price = input('Input Buy/Sell Price > ')

update_tbl = [i_date, i_trans, i_symbol, i_qty, i_price]


def update_table(date, trans, symbol, qty, price):
    c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', update_tbl)

update_table(i_date, i_trans, i_symbol, i_qty, i_price)

标签: pythonsqlite

解决方案


使用传递给函数的参数在函数内部创建 update_tbl。您的第一个解决方案的问题是您正在创建一个包含 1 个项目的列表。这是因为您将所有输入连接成 1 个字符串。

i_date = input('Input Date as YYYY-MM-DD > ')
i_trans = input('Select Buy or Sell > ')
i_symbol = input('Input Stock Ticker > ')
i_qty = input('Input Qty to be Purchased > ')
i_price = input('Input Buy/Sell Price > ')


def update_table(date, trans, symbol, qty, price):
    update_tbl = [date, trans, symbol, qty, price]
    c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', update_tbl)


update_table(i_date, i_trans, i_symbol, i_qty, i_price)

推荐阅读