pandas 大熊猫到sql server

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36487153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:00:35  来源:igfitidea点击:

pandas to sql server

pythonsqlsql-serverpandas

提问by JOHN

I got following code. The problem is I could read data use panda.read_sql, but I could not use the DataFrame.to_sql() function.

我得到了以下代码。问题是我可以使用 panda.read_sql 读取数据,但我无法使用 DataFrame.to_sql() 函数。

%matplotlib inline
import pandas as pd
import pyodbc
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt

pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 15)
pd.set_option('precision', 4)

conn = pyodbc.connect(r"Driver={SQL Server};Server=dev;Database=test1")

data = pd.read_sql_query(
    """
SELECT *
FROM   sys.tables
    """
    , con = conn)

print data
data.to_sql('test', con = conn)

the error is the following:

错误如下:

Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")

sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;' 执行失败:('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]无效的对象名称'sqlite_master' . (208) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server 驱动程序][SQL Server]无法准备语句。(8180)")

Is there a way to get around?

有没有办法绕过?

回答by Parfait

Consider creating a sqlalchemy MSSQL engineand use that in pandas to_sql()con argument:

考虑创建一个 sqlalchemy MSSQL 引擎并在 pandas to_sql()con 参数中使用它:

import sqlalchemy

...
engine = sqlalchemy.create_engine(
               "mssql+pyodbc://user:pwd@server/database",
               echo=False)

data.to_sql('test', con=engine, if_exists='replace')