Python 在尝试使用to_sql函数插入时,数据库引擎无法连接到sql server实例

Python 在尝试使用to_sql函数插入时,数据库引擎无法连接到sql server实例,python,sql-server,pandas,database-connection,Python,Sql Server,Pandas,Database Connection,我正在尝试使用dataframe.to_SQL将pandas dataframeCAPE插入到SQL ServerDB中。我引用了下面的解决方案来插入行。 但我得到一个错误如下所示 源代码: CAPE # Input dataframe connection = pdc.connect('Driver={SQL Server};''Server=GIRSQL.GIRCAPITAL.com;''Database=Tableau;''uid=SQL_User;pwd=Greent

我正在尝试使用dataframe.to_SQL将pandas dataframe
CAPE
插入到
SQL Server
DB中。我引用了下面的解决方案来插入行。

但我得到一个错误如下所示

源代码:

   CAPE    # Input dataframe
   connection = pdc.connect('Driver={SQL Server};''Server=GIRSQL.GIRCAPITAL.com;''Database=Tableau;''uid=SQL_User;pwd=Greentableau!')
   connection_string = urllib.parse.quote_plus(connection)
   connection_string = "mssql+pyodbc:///?odbc_connect=%s" % connection_string
   engine = sq.create_engine(connection_string)
   CAPE.to_sql(engine, name='[Tableau].[dbo].[Company_Table]',if_exists='replace')
这就是我得到的错误:

    Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Abhay\Python36-32\lib\urllib\parse.py", line 803, in quote_plus
string = quote(string, safe + space, encoding, errors)
  File "C:\Users\Abhay\Python36-32\lib\urllib\parse.py", line 787, in quote
 return quote_from_bytes(string, safe)
  File "C:\Users\Abhay\Python36-32\lib\urllib\parse.py", line 812, in quote_from_bytes
  raise TypeError("quote_from_bytes() expected bytes")
  TypeError: quote_from_bytes() expected bytes
  connection = pdc.connect('Driver={SQL Server};''Server=GIRSQL.GIRCAPITAL.com;''Database=Tableau;''uid=SQL_User;pwd=Greentableau!')
   connection_string = ur.quote(connection)
  Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Abhay\Python36-32\lib\urllib\parse.py", line 787, in quote
return quote_from_bytes(string, safe)
  File "C:\Users\Abhay\Python36-32\lib\urllib\parse.py", line 812, in 
 quote_from_bytes
  raise TypeError("quote_from_bytes() expected bytes")
  TypeError: quote_from_bytes() expected bytes

的第一个位置参数是表名,您将
引擎
(SQLAlchemy对象)作为第一个参数传递

因此,请尝试以下方法:

CAPE.to_sql('[Tableau].[dbo].[Company_Table]',con=engine, if_exists='replace')

调用_sql之前,我在“urllib.parse.quote_plus()”行中遇到错误。是否有更好的方法将数据帧插入Sql server数据库我已将代码更改为以下内容(“驱动程序={Sql server};服务器=GIRSQL.GIRCAPITAL.com;数据库=Tableau;UID=Sql\u用户;PWD=greenttableau!”)引擎=sqlalchemy.create\u引擎(“mssql+pyodbc://?odbc\u connect=%s”%params)引擎。connect()到Sql(name='[Tableau].[dbo].[testtable]',con=engine,index=False,如果_exists='append')
CAPE.to_sql('[Tableau].[dbo].[Company_Table]',con=engine, if_exists='replace')