python - 在 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)
解决方案
使用传递给函数的参数在函数内部创建 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)
推荐阅读
- wget - 谁能教我安装 wget 到 git bash
- reactjs - 当我在 Mac 和 PC 上运行相同的代码时,在 PC 上出现“resolve-url-loader:CSS 错误”
- python - 在 Python 中自定义颜色栏(截断并添加更多颜色)
- reactjs - 表情符号未在 React 应用程序中呈现,terser 插件构建失败
- vb.net - 将 StartIndex 调暗为整数 Step
- nginx - nginx 中 $request_length 的单位是什么?
- tmux - tmux - 如何使用特殊标记来指示特定的窗口和/或窗格
- javascript - 重新分配输入字段,使用 JQuery 和 JavaScript 的简单计算器
- sql - SQL:使用 OR 进行 Equi 连接
- java - /帮助
有效,实际命令什么也不返回。我的世界 1.14.4 插件