вставка данных в SQL Сервер БД с использованием sqlalchemy выдает ошибку: объект «Соединение» не имеет атрибута «курсор» - PullRequest
0 голосов
/ 30 января 2020

Я просто пытаюсь вставить фрейм данных в sql базу данных сервера, используя sqlalchemy.

Чего мне здесь не хватает?

import sqlalchemy
engine = sqlalchemy.create_engine('mssql+pyodbc://01.01.01.01/MYDB?driver=SQL+Server', echo=False)
conn = engine.connect()
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }
df = pd.DataFrame(Cars, columns= ['Brand', 'Price'])

df.to_sql('CARS', conn, if_exists='replace', index = False, schema='dbo')

Ошибка:

AttributeError                            Traceback (most recent call last)
<ipython-input-258-8c90e225f0fb> in <module>
      8 df = pd.DataFrame(Cars, columns= ['Brand', 'Price'])
      9 
---> 10 df.to_sql('CARS', conn, if_exists='replace', index = False, schema='dbo')
     11 #df.to_sql('book_details', con = engine, if_exists = 'replace', chunksize = 1000)

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)to_sql(self, name, con, schema, if_exists, index, index_label, chunksize, dtype, method)
   2710             chunksize=chunksize,
   2711             dtype=dtype,
-> 2712             method=method,
   2713         )
   2714 

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)to_sql(frame, name, con, schema, if_exists, index, index_label, chunksize, dtype, method)
    516         chunksize=chunksize,
    517         dtype=dtype,
--> 518         method=method,
    519     )
    520 

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)
to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype, method)
   1747             dtype=dtype,
   1748         )
-> 1749         table.create()
   1750         table.insert(chunksize, method)
   1751 

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)create(self)
    639 
    640     def create(self):
--> 641         if self.exists():
    642             if self.if_exists == "fail":
    643                 raise ValueError(

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)n exists(self)
    626 
    627     def exists(self):
--> 628         return self.pd_sql.has_table(self.name, self.schema)
    629 
    630     def sql_schema(self):

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)has_table(self, name, schema)
   1760         ).format(wld=wld)
   1761 
-> 1762         return len(self.execute(query, [name]).fetchall()) > 0
   1763 
   1764     def get_table(self, table_name, schema=None):

c:\users\username\pandas\io\sql.py in execute(self, *args, **kwargs)
   1588             cur = self.con
   1589         else:
-> 1590             cur = self.con.cursor()
   1591         try:
   1592             if kwargs:

AttributeError: 'Connection' object has no attribute 'cursor'

ОБНОВЛЕНИЕ:

Список модулей и их версия, которую я использую:

 PS Z:\> pip freeze                                                                                                      attrs==19.3.0
backcall==0.1.0
bleach==3.1.0
colorama==0.4.3
cycler==0.10.0
decorator==4.4.1
defusedxml==0.6.0
entrypoints==0.3
et-xmlfile==1.0.1
importlib-metadata==1.3.0
ipykernel==5.1.3
ipython==7.10.2
ipython-genutils==0.2.0
ipywidgets==7.5.1
jdcal==1.4.1
jedi==0.15.1
Jinja2==2.10.3
json5==0.8.5
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==5.3.4
jupyter-console==6.0.0
jupyter-core==4.6.1
jupyterlab==1.2.4
jupyterlab-server==1.0.6
kiwisolver==1.1.0
lab==5.1
MarkupSafe==1.1.1
matplotlib==3.1.2
mistune==0.8.4
more-itertools==8.0.2
nbconvert==5.6.1
nbformat==4.4.0
notebook==6.0.2
numpy==1.17.4
openpyxl==3.0.3
pandas==0.25.3
pandocfilters==1.4.2
parso==0.5.2
pickleshare==0.7.5
prometheus-client==0.7.1
prompt-toolkit==2.0.10
Pygments==2.5.2
PyMySQL==0.9.3
pyodbc==4.0.27
pyparsing==2.4.5
pyrsistent==0.15.6
python-dateutil==2.8.1
pytz==2019.3
pywin32==227
pywinpty==0.5.7
pyzmq==18.1.1
qtconsole==4.6.0
Send2Trash==1.5.0
simplejson==3.17.0
six==1.13.0
SQLAlchemy==1.3.13
terminado==0.8.3
testpath==0.4.4
tornado==6.0.3
traitlets==4.3.3
wcwidth==0.1.7
webencodings==0.5.1
widgetsnbextension==3.5.1
xlrd==1.2.0
zipp==0.6.0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...