【问题标题】:Insert int and string values into a mysql table将 int 和 string 值插入到 mysql 表中
【发布时间】:2019-01-21 17:42:03
【问题描述】:

我有一个这样的列表:

[4000, 5000, 6000, 'No price', 0, 'No price']

我想迭代列表并将值插入到 mysql 表中。 我为表定义了 int 值,因此,由于字符串类型,它无法在表中插入“无价格”。我想插入 None 值而不是字符串值。我怎么解决这个问题?这是我的代码:

for price, operation in zip(cost_list,mile_list):
    add_cars = "INSERT INTO car_list(price, operation) VALUES(%s, %s)"
    val = (price, operation)
    cursor.execute(add_cars, val)

【问题讨论】:

  • 请显示您遇到问题的代码。另外,由于不可能将字符串放入 int 字段中,您想在其位置放入什么(如果有的话)?
  • 请包含所有相关代码。仔细检查您的 IDE 中是否有错误,因为这里有一个错误 0',
  • 创建可为空的 int 字段并在其中放置一个空值 - 或创建一个表示没有价格的“默认”值 - 例如。 -1
  • no priceprice = 0 有什么区别?为什么不直接使用0
  • @Barmar 因为有些产品的价格是 0,有些因为缺少数据而没有价格

标签: python mysql


【解决方案1】:

您可以检查变量是否为整数,如果不是,则将其替换为默认值。

add_cars = "INSERT INTO car_list(price, operation) VALUES(%s, %s)"
for price, operation in zip(cost_list,mile_list):
    if not isinstance(price, int):
        price = None
    val = (price, operation)
    cursor.execute(add_cars, val)

【讨论】:

  • 我必须在没有价格的单元格中插入 None 或 Null 值
  • 然后使用None作为默认值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多