【问题标题】:How to write dataframe into mssql using pymssql?如何使用 pymssql 将数据帧写入 mssql?
【发布时间】:2017-01-18 14:52:39
【问题描述】:

我正在使用 pymssql 将 df 写入 mssql,但没有成功。

from sqlalchemy import create_engine
import pymssql
engine = create_engine('mssql+pymssql://sa:suzhou@localhost/test_python')

data.to_sql('phill',engine)

出现以下错误。怎么了?

NoSuchColumnError: "Could not locate column in row for column '0'"

前 5 行:

    Dc_Dist Psa Dispatch_Date_Time  Dispatch_Date   Dispatch_Time   Hour    Dc_Key  Location_Block  UCR_General Text_General_Code   Police_Districts    Month   Lon Lat
3   35  D   2009-07-19 01:09:00 2009-07-19  01:09:00    1   200935061008    5500 BLOCK N 5TH ST 1500.0  Weapon Violations   20.0    2009-07 -75.130477  40.036389
4   9   R   2009-06-25 00:14:00 2009-06-25  00:14:00    0   200909030511    1800 BLOCK WYLIE ST 2600.0  All Other Offenses  8.0 2009-06 -75.166350  39.969532
5   17  1   2015-04-25 12:50:00 2015-04-25  12:50:00    12  201517017705    800 BLOCK S BROAD ST    600.0   Thefts  13.0    2015-04 -75.166412  39.940070
6   23  K   2009-02-10 14:33:00 2009-02-10  14:33:00    14  200923006310    2200 BLOCK RIDGE AVE    800.0   Other Assaults  16.0    2009-02 -75.171149  39.979586
12  22  3   2015-10-06 18:18:00 2015-10-06  18:18:00    18  201522089374    1500 BLOCK N 15TH ST    600.0   Thefts  16.0    2015-10 -75.160229  39.976134

【问题讨论】:

    标签: python sql-server pandas pymssql


    【解决方案1】:

    猜测 SQL Server 不喜欢像 0 这样的列名,因此您必须在将 DF 写入 SQL Server 之前重命名列。

    所以您可以尝试以下解决方案:

    data.add_prefix('col_').to_sql('phill',engine)
    

    【讨论】:

    • 没有像 0、Index([u'Dc_Dist', u'Psa', u'Dispatch_Date_Time', u'Dispatch_Date', u'Dispatch_Time', u'Hour', u'Dc_Key', u'Location_Block', u'UCR_General', u'Text_General_Code', u'Police_Districts', u'Month', u'Lon', u'Lat'], dtype='object')engine = create_engine('mssql+pymssql://sa:suzhou@localhost/test_python') 这样的列名对吗?
    • @runningman,对不起,在这种情况下我不知道...尝试谷歌搜索SQLAlchemy + NoSuchColumnError: "Could not locate column in row for column"
    • Tks 都是一样的 MaxU。我在另一台电脑上做。有用。也许这是我的数据库的问题。
    【解决方案2】:
    from sqlalchemy import create_engine
    import pyodbc
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(index=range(3), columns=range(3), data=np.zeros((3,3)))
    engine = create_engine("mssql+pyodbc://.\SQLEXPRESS/test_python?driver=SQL server")
    
    df.to_sql('test', con=engine)
    

    在本地服务器上工作正常,但使用 pyodbc。你的数据框是什么样的?

    【讨论】:

      【解决方案3】:

      问题出在sqlalchemy。在我的 python 坐包中,有SQLAlchemy-1.1.4-py2.7.egg-infoSQLAlchemy-1.1.5.dist-infosqlalchemy。把sqlalchemy以外的都删掉,NoSuchColumnError: "Could not locate column in row for column '0'"就解决了。

      【讨论】:

        猜你喜欢
        • 2015-11-25
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多