取得 SQL 資料時出錯
P粉648469285
2023-09-04 17:09:42
<p>所以我只是從資料庫中提取數據,遇到以下錯誤。
代碼如下:</p>
<pre class="brush:php;toolbar:false;">import pandas as pd
import sqlalchemy
engine = sqlalchemy.create_engine("mysql pymysql://root:@localhost:3306/haider")
df = pd.read_sql_table("ahmed", engine)</pre>
<p>執行此程式碼時出現以下錯誤:</p>
<pre class="brush:php;toolbar:false;">--------------------------------- ------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [46], line 1
----> 1 df = pd.read_sql_table("ahmed", engine)
File E:\python\lib\site-packages\pandas\io\sql.py:286, in read_sql_table(table_name, con, schema, index_col, coerce_float, parse_dates, columns, chunksize)
282 raise ValueError(f"Table {table_name} not found")
284 # error: Item "SQLiteDatabase" of "Union[SQLDatabase, SQLiteDatabase]"
285 # 有 no attribute "read_table"
--> 286 table = pandas_sql.read_table( # type: ignore[union-attr]
287 table_name,
288 index_col=index_col,
289 coerce_float=coerce_float,
290 parse_dates=parse_dates,
291 columns=columns,
292 chunksize=chunksize,
293 )
295 if table is not None:
296 return table
File E:\python\lib\site-packages\pandas\io\sql.py:1460, in SQLDatabase.read_table(self, table_name, index_col, coerce_float, parse_dates, columns, schema, chunksize)
1417 """
1418 Read SQL database table into a DataFrame.
1419
(...)
1457
1458 """
1459 table = SQLTable(table_name, self, index=index_col, schema=schema)
-> 1460 return table.read(
1461 coerce_float=coerce_float,
1462 parse_dates=parse_dates,
1463 columns=columns,
1464 chunksize=chunksize,
1465 )
File E:\python\lib\site-packages\pandas\io\sql.py:1003, in SQLTable.read(self, coerce_float, parse_dates, columns, chunksize)
1001 else:
1002 sql_select = select(self.table)
-> 1003 result = self.pd_sql.execute(sql_select)
1004 column_names = result.keys()
1006 if chunksize is not None:
File E:\python\lib\site-packages\pandas\io\sql.py:1405, in SQLDatabase.execute(self, *args, **kwargs)
1403 def execute(self, *args, **kwargs):
1404 """Simple passthrough to SQLAlchemy connectable"""
-> 1405 return self.connectable.execution_options().execute(*args, **kwargs)
AttributeError: 'OptionEngine' object has no attribute 'execute'</pre>
<p>注意:我的資料庫沒有任何密碼,其次我也已經安裝了 PyMySQL。 </p>
<p>我試圖解釋使用 python 獲取 sql 資料時遇到的錯誤,我希望得到該問題的解決方案。 </p>
我強烈建議您嘗試以下操作
我認為您可能缺少最後的 connect() 部分。