|
Python. Pandas+SQL. Метод to_sql выдает странные ошибки | ☑ | ||
---|---|---|---|---|
0
megabax
18.11.19
✎
18:30
|
Добрый день.
Подскажите, пожалуйста, что делаю не так: Выполняю такой код: import pyodbc import pandas as pd driver = 'DRIVER={SQL Server}' server = 'SERVER=MEGABAX\SQLEXPRESS' port = 'PORT=1433' db = 'DATABASE=Python' user = 'UID=логин' pw = 'PWD=пароль' conn_str = ';'.join([driver, server, port, db, user, pw]) conn = pyodbc.connect(conn_str) cursor = conn.cursor() nr_customers=100 colnames=["movie%d" %i for i in range(1,33)] pd.np.random.seed(2015) generated_customers=pd.np.random.randint(0,2,32*nr_customers).reshape(nr_customers,32) data=pd.DataFrame(generated_customers, columns=list(colnames)) data.to_sql('cust',conn,index=True,if_exists='replace',index_label='cust_id') На строке data.to_sql('cust',conn,index=True,if_exists='replace',index_label='cust_id') Выдает ошибку: ProgrammingError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs) 1430 else: -> 1431 cur.execute(*args) 1432 return cur ProgrammingError: ('42S02', '[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Недопустимое имя объекта "sqlite_master". (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Не удалось выполнить подготовку инструкций. (8180)') During handling of the above exception, another exception occurred: DatabaseError Traceback (most recent call last) <ipython-input-20-85dbdc50e597> in <module> 19 data=pd.DataFrame(generated_customers, columns=list(colnames)) 20 #print(data) ---> 21 data.to_sql('cust',conn,index=True,if_exists='replace',index_label='cust_id') 22 ~\Anaconda3\lib\site-packages\pandas\core\generic.py in to_sql(self, name, con, schema, if_exists, index, index_label, chunksize, dtype, method) 2529 sql.to_sql(self, name, con, schema=schema, if_exists=if_exists, 2530 index=index, index_label=index_label, chunksize=chunksize, -> 2531 dtype=dtype, method=method) 2532 2533 def to_pickle(self, path, compression='infer', ~\Anaconda3\lib\site-packages\pandas\io\sql.py in to_sql(frame, name, con, schema, if_exists, index, index_label, chunksize, dtype, method) 458 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, 459 index_label=index_label, schema=schema, --> 460 chunksize=chunksize, dtype=dtype, method=method) 461 462 ~\Anaconda3\lib\site-packages\pandas\io\sql.py in to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype, method) 1544 if_exists=if_exists, index_label=index_label, 1545 dtype=dtype) -> 1546 table.create() 1547 table.insert(chunksize, method) 1548 ~\Anaconda3\lib\site-packages\pandas\io\sql.py in create(self) 570 571 def create(self): --> 572 if self.exists(): 573 if self.if_exists == 'fail': 574 raise ValueError( ~\Anaconda3\lib\site-packages\pandas\io\sql.py in exists(self) 558 559 def exists(self): --> 560 return self.pd_sql.has_table(self.name, self.schema) 561 562 def sql_schema(self): ~\Anaconda3\lib\site-packages\pandas\io\sql.py in has_table(self, name, schema) 1556 "WHERE type='table' AND name={wld};").format(wld=wld) 1557 -> 1558 return len(self.execute(query, [name, ]).fetchall()) > 0 1559 1560 def get_table(self, table_name, schema=None): ~\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs) 1443 "Execution failed on sql '{sql}': {exc}".format( 1444 sql=args[0], exc=exc)) -> 1445 raise_with_traceback(ex) 1446 1447 @staticmethod ~\Anaconda3\lib\site-packages\pandas\compat\__init__.py in raise_with_traceback(exc, traceback) 418 if traceback == Ellipsis: 419 _, _, traceback = sys.exc_info() --> 420 raise exc.with_traceback(traceback) 421 else: 422 # this version of raise is a syntax error in Python 3 ~\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs) 1429 cur.execute(*args, **kwargs) 1430 else: -> 1431 cur.execute(*args) 1432 return cur 1433 except Exception as exc: DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', '[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Недопустимое имя объекта "sqlite_master". (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Не удалось выполнить подготовку инструкций. (8180)') |
|||
1
Salimbek
19.11.19
✎
08:55
|
(0) Недопустимое имя объекта "sqlite_master"
Ни о чем вам не сказало? |
|||
2
Salimbek
19.11.19
✎
08:59
|
+(1) Тут: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html#pandas.DataFrame.to_sql
Описание второго параметра con : sqlalchemy.engine.Engine or sqlite3.Connection Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. |
|||
3
Salimbek
19.11.19
✎
09:06
|
||||
4
megabax
19.11.19
✎
19:23
|
Спасибо.
То есть, как я понял, либо нужно использовать SQLAlchemy, либо тупо инсертить записи в цикле? |
|||
5
Asmody
19.11.19
✎
19:45
|
Алхимию использовать религия не позволяет?
|
Форум | Правила | Описание | Объявления | Секции | Поиск | Книга знаний | Вики-миста |