【发布时间】: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