【问题标题】:Can I create a loop to update SQL database?我可以创建一个循环来更新 SQL 数据库吗?
【发布时间】:2016-12-15 04:28:46
【问题描述】:

我的sql.db 文件中有 6 个表。我想知道是否可以创建一个循环来遍历这 6 个表中的每一列,如果单元格值为-,则将值转换为NULL

我目前拥有的代码

for each_item in df.index:  
# Note: The name of the tables in the database is the variable 'each_item'
    pd.Dataframe.to_sql(df, con=engine, name=each_item, if_exists='append', index=False)

    # The below code does not work. And I have no idea why
    for each_columns in df.columns:
        connection.execute('UPDATE each_item SET each_columns = NULL WHERE each_columns = '-')

这似乎产生了错误。

如果单元格值 = -,我应该如何对其进行编码,以便能够遍历 sql.db 中的所有 tables,并更新 tables 中的每个 column ?

更具体地说,我得到的错误是它无法找到表格。 no such table: each_item

【问题讨论】:

  • tbh id 只是把它放在一个while循环中
  • 谢谢,但这对我的问题没有帮助。如果我将表名放在变量中,似乎无法找到tables
  • 连接到服务器了吗?
  • 你的6张桌子的名字在哪里?您使用的是哪种 SQL DB?

标签: python sql pandas sqlalchemy


【解决方案1】:

好的,您的代码中存在很多问题。让我们一次解决每个问题:

  1. 在这种情况下,pd.DataFrame.to_sql 代表 your_dataframe.to_sqldf.to_sql。它是DataFrame 对象上的一个方法,该对象就是您创建的DataFrame。如果这让您感到困惑,请阅读 Python 中的类和方法。
  2. to_sql 将其第一个参数作为表名,然后是连接,然后是模式名,最后是 if_exists 和索引 kwag
  3. 最好在尝试写入 SQL 之前完成所有转换。这只会让事情变得更干净。此外,如果您的 DataFrame 数据类型正确,NaN 值将自动转换为相关数据库引擎的适当 NULL 值表示。

如果您考虑以上所有要点,应该这样做:

for each_item in df.index: # I would avoid a syntax like this. Better to have the DataFrames in a list, than iterate through a DataFrame
    df.loc[each_item].to_sql(name=each_item, con=engine, if_exists='append', index=False) # Here again, I would avoid using the name engine for a connection to a database engine

但是,上述代码的成功取决于您的 DataFrame 是否正确输入了数据,我认为这不是因为您问了这个问题。如果您使用 DataFrame 示例编辑您的问题,我将能够帮助您正确设置数据类型。


附言。如果您的 DataFrame 是由于您之前关于 DataFrame 合并的问题而创建的,那么请告诉我,我将在此处为您提供这两个问题的全面解决方案。但请务必使用来自该问题的数据编辑此问题,以免阅读此问题的人被难倒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多