代码之家  ›  专栏  ›  技术社区  ›  Umar.H

使用不使用append的新列将df写入sql dB

  •  0
  • Umar.H  · 技术社区  · 6 年前

    尝试使用pandas/sql炼金术进行一些自学。我已经在本地系统上设置了一个虚拟数据库ms SQL 2012(我们在工作中使用的数据库),我可以

    使用更新并追加新行

    将所有目标行替换为 df with if_exists='replace'

    现在我搞不清楚的是,这可能是因为我不知道如何在我的数据库中写入带有附加列的数据帧。

    从数据库中提取以下df

       stores = np.random.choice(800,5,replace=True)
    week1 = np.random.randint(1,500,size=5)
    df = pd.DataFrame({'Stores' : stores,'Week 1' : week1})
        print(df)
        Stores  Week 1
    0   461 413
    1   568 181
    2   793 173
    3   349 49
    4   713 258
    

    现在,如果我想用现有列和新行来更新它,这会像预期的那样完美,但是如果我创建一个新列:

    df['Week 2'] = np.random.randint(1,500,size=len(df)) 
    

    我在使用时遇到以下错误:

    df.to_sql(name='my table',
    con = engine,
    index=False,
    if_exists='append')
    
    
    
        ProgrammingError: ('42S22', "[42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Week 2'. (207) (SQLExecDirectW); [42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Week 2'. (207); [42S22] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")
    
    The above exception was the direct cause of the following exception:
    

    如有任何帮助/文档指导,我们将一如既往地不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Damian    6 年前

    正如错误描述中所写,“Week 2”是Mysql中不可接受的表列名称 “列名称“第2周”无效。”

    编程错误:('42S22',“[42S22][Microsoft][SQL Server本机客户端11.0][SQL Server] 列名称“第2周”无效 . (207)(SQLExecDirectW);[42S22][Microsoft][SQL Server本机客户端11.0][SQL Server] 列名“1956”无效。

    它应该能正常工作。

    df['Week2'] = np.random.randint(1,500,size=len(df)) 
    

    它还将“1956”作为列名,但我不知道这是否是因为以前的错误,所以请先更正此列;)