我有一个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)
此代码不会更改我的数据库中的任何内容,并且无任何错误。
答案 0 :(得分:0)
您需要提交并关闭您打开的光标,以便在DB.Add中看到更改
connection.commit()
cursor.close()
connection.close()
最后检查更改是否反映在数据库中。