【问题标题】:Why wiil not my program insert to the database?为什么我的程序不能插入数据库?
【发布时间】:2018-07-17 10:45:39
【问题描述】:

我制作了一个程序,因为它适用于简单的 Excel 工作表,所以它的行为表现很奇怪。

我可以简单描述一下我的问题:

  1. 也是 Hour disappers 的头部,我尝试了 header = None 和 parscols = ["", ""],但头部仍然不会加入数据库

  2. excel表格的数值不会入库,虽然我已经避免了缺失数据。

这是我的代码:

from src.server.connectToDB import get_sql_conn
import pandas as pd


if __name__ == '__main__':
    cursor = get_sql_conn().cursor()
    local_files = 'C:\\Users\\dersimw\\Source\Repos\\nordpoolAnalyse\\data\\2011-3.xlsx'
    excelFile = pd.ExcelFile(local_files)

    ark = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15",
         "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"]

    for sheets in ark:
        df = excelFile.parse(sheets).head(5)
        print(df.dropna(axis=1, how='all'))
        for key, rows in df.items():
            print("# Kolonne: ", "\n")
            columnInsertSql = "INSERT INTO DataSets (Hour, BlockBuyNet, BlockSell, RejectedBlockBuy, RejectedBlockSell, NetImports) VALUES"
            rowCounter = 0

            for column in rows.items():
                columnInsertSql += str(column)

                if rowCounter != len(list(rows.items())):
                    columnInsertSql += ", "
                rowCounter += 1

            print("## SQL: " + columnInsertSql)

            cursor.execute(columnInsertSql)
            cursor.commit()

这是我打印df.dropna (axis = 1, how = 'all')时的结果:

小时 0 1 ... 21 22 23

0 接受大宗购买 112 112 ... 227 52 52

1 接受大宗卖出 1573.2 1575.2 ... 1833.8 1728.3 1649.3

2 拒绝块购买 NaN NaN ... NaN NaN NaN

3 拒绝大宗卖出 NaN NaN ... NaN NaN NaN

4 净进口 2652.3 2505.9 ... 2932 2962 2897

【问题讨论】:

  • print("## SQL: " + columnInsertSql) 打印什么?
  • 这一行将打印出:INSERT INTO DataSets (Hour, BlockBuyNet, BlockSell, RejectedBlockBuy, RejectedBlockSell, NetImports) VALUES(0, 'Accepted Block Buy'), (1, 'Accepted Block Sell' ), (2, '拒绝大宗买入'), (3, '拒绝大宗卖出'), (4, '净进口'),
  • 您的 INSERT 命名了 5 列,但您的 VALUES 子句仅指定了 2 个值。
  • 好的,谢谢,你有什么想法我可以解决它吗?

标签: python sql-server excel pandas


【解决方案1】:

看起来您正在尝试删除 NA,但您忘记放置“inplace”标志,这就是为什么当打印出数据框时,您似乎没有任何缺失值的行,但原始 Df 保持不变。

 for sheets in ark:
    df = excelFile.parse(sheets).head(5)
    df.dropna(axis=1, how='all', inplace=True)

您也可以像这样重新声明 DF:

 for sheets in ark:
    df = excelFile.parse(sheets).head(5)
    df = df.dropna(axis=1, how='all')

另外,我建议使用 Pandas to_sql 功能让您的生活更轻松。 您可以像这样一次上传整个 DF 而不是一行:

from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')

#Fill in your code to loop through workbooks here

for sheets in ark:
    df = excelFile.parse(sheets).head(5)
    df = df.dropna(axis=1, how='all')
    df.columns =['Hour','BlockBuyNet','BlockSell','RejectedBlockBuy','RejectedBlockSell','NetImports']
    df.to_sql('DataSets', con = engine, if_exists='append', index = False)

【讨论】:

  • 谢谢安东!我从未使用过 create_engine 并且我是初学者。应该把 scott:tiger 换成我自己的名字吗?在这段代码中我可以在哪里输入 excel 表?
  • @Dersimwaisi 是的,您将不得不根据您的 SQL 引擎、用户名、密码等更改您的 sql 连接要求。您可以在此处找到更多信息:docs.sqlalchemy.org/en/latest/core/engines.html 重新循环遍历 excel 表;你可以使用你已经写好的代码。不明白为什么它不起作用。
  • 谢谢你,安东·彼得罗修克。我更喜欢使用 read_excel .. 但是当我使用 read_excel 然后使用 ExcelFile 时解析将不起作用。我不知道为什么当我从 read_excel 切换到 Excelfile 时解析不起作用
猜你喜欢
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 2015-12-13
  • 2019-09-07
  • 1970-01-01
相关资源
最近更新 更多