【问题标题】:How to update each and every NULL value in a column to zero?如何将列中的每个 NULL 值更新为零?
【发布时间】:2017-12-13 16:29:03
【问题描述】:

我有一个 sqlite3 数据库。它在某些列中有一些 NULL 值。 我想要的是遍历每一列并将 NULL 值更新为 0? 我可以使用 pandas 来做到这一点,但我想知道是否可以使用 sqlite3 来做到这一点。 如果可能,那么在 MySQL 中是否可以使用相同的命令。?

代码:

import sqlite3 as sql

#connect to database
connection = sql.connect("ADARSH.db")

#make a cursor which will move in the database
cursor = connection.cursor()

#execute the different command
def execute(cursor, command):
    return cursor.execute(command)

#print the result
def print_result(result):
    for var in result:
        print(var)

# select every column name
command = """select * from emplyee where 1=0"""
result = execute(cursor, command)

# and store it in a list
col_list = [d[0] for d in result]

#for every column name, replace NULL value with 0
def update_null(cursor, col_list):
    for each_col in col_list:
        command = "update emplyee set {col_name}='0' where {col_name} is null".format(
                    col_name=each_col)
        execute(cursor, command)

update_null(cursor, col_list)
command = """select * from emplyee """
result = execute(cursor, command)
print_result(result)

此代码不会更改我的数据库中的任何内容,并且它可以正常工作而不会出现任何错误。

【问题讨论】:

  • 1=0 里面的东西在做什么?这绝不是真的。
  • 是的,它通过我的数据库收集每个列名。
  • 这是获取该列表的一种非常奇怪的方式。我也不确定您是否可以随意将所有内容归零。为什么不将这些列的默认值设置为0 并禁止NULL
  • 它虽然有效,但问题是一旦我在列表中获得列,我循环遍历每一列并将其更新为 0,但不知何故它不起作用。我可以禁止 NULL 值,但假设它是由某人提供给我的。以数据预处理的方式思考
  • 如果它不起作用,或者您没有发出正确的命令,或者您没有看到错误。我认为这段代码很奇怪,因为它也使用了游标。这可能是问题的根源。

标签: mysql python-3.x sqlite


【解决方案1】:

您需要提交并关闭您打开的光标才能在 DB.Add 中看到更改

connection.commit()
cursor.close()
connection.close()

最后检查更改是否反映在数据库中。

【讨论】:

  • 不,它不起作用。此外,这不是提交数据库中的更改,而是临时更改数据库,然后将其用于您的特定目的。谁知道如果我们更改数据库会带来什么后果。
  • 你确定你得到了 col_list 中的名字吗?在创建 col_list 后立即插入打印语句进行检查
  • 并且 select * from emplyee 不会给你列名,而是每行的列中的值,所以你不能在更新语句中使用它。
  • 谢谢!正如我提到的问题不在 col-list 中,我已经使用过很多次了,如果您对此有疑问,我可以发布链接。在 select* 之后有 1=0 的东西让我得到列名
猜你喜欢
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
相关资源
最近更新 更多