oll*_*end 4 python mysql sqlalchemy pandas pymysql
我正在尝试使用 Pandas (v1.3.4)、SQLAlchemy (v1.4.26) 和 PyMySQL (v1.0.2) 写入 MySQL 数据库。我可以使用 pandas 创建一个新表(称为“test_table”)to_sql方法创建一个新表(称为“test_table”),但随后尝试写入同一个表会给出:
OperationalError: (pymysql.err.OperationalError) (1050, "Table 'test_table' already exists")
Run Code Online (Sandbox Code Playgroud)
我之前在 SQLite 中完成过此操作,所以我不确定为什么它在 MySQL 中不起作用。这是我的语法问题,还是数据库服务器配置中可能需要更改某些内容?
这是我正在使用的代码。
首先,导入并建立与数据库服务器的连接:
from sqlalchemy import create_engine
import pymysql
import pandas as pd
sqlEngine = create_engine('mysql+pymysql://username:password@127.0.0.1', pool_recycle=3600)
con = sqlEngine.connect()
Run Code Online (Sandbox Code Playgroud)
建立具体的数据库名称:
sql = '''
USE my_database
'''
con.execute(sql);
Run Code Online (Sandbox Code Playgroud)
生成一个条目并写入名为的新表test_table:
entry = pd.DataFrame({
'PersonID': 0,
'LastName': 'smith',
'FirstName': 'joe',
}, index=[0])
entry.to_sql('test_table', con, if_exists='append')
Run Code Online (Sandbox Code Playgroud)
验证我的条目是否已进入表中:
entry = pd.DataFrame({
'PersonID': 0,
'LastName': 'smith',
'FirstName': 'joe',
}, index=[0])
entry.to_sql('test_table', con, if_exists='append')
Run Code Online (Sandbox Code Playgroud)
这使:
到目前为止,一切都很好。现在,我尝试test_table使用参数在我的表中添加一个新条目,if_exists='append'以便新条目将附加到现有表的末尾:
entry = pd.DataFrame({
'PersonID': 1,
'LastName': 'smith',
'FirstName': 'mary',
}, index=[0])
entry.to_sql('test_table', con, if_exists='append')
Run Code Online (Sandbox Code Playgroud)
结果是:
sql = '''
SELECT *
FROM test_table
'''
pd.read_sql_query(sql, con)
Run Code Online (Sandbox Code Playgroud)
为什么 Pandas 试图在这里创建一个新表?如何强制它附加到现有表中?
小智 6
我遇到了同样的问题,我找到了两种方法来解决它,尽管我不知道为什么会解决它:
pd.to_sql。两者都做并没有坏处。
```
#create connection to MySQL DB via sqlalchemy & pymysql
user = credentials['user']
password = credentials['password']
port = credentials['port']
host = credentials['hostname']
dialect = 'mysql'
driver = 'pymysql'
db_name = 'test_db'
# setup SQLAlchemy
from sqlalchemy import create_engine
cnx = f'{dialect}+{driver}://{user}:{password}@{host}:{port}/'
engine = create_engine(cnx)
# create database
with engine.begin() as con:
con.execute(f"CREATE DATABASE {db_name}")
############################################################
# either pass the db_name vvvv - HERE- vvvv after creating a database
cnx = f'{dialect}+{driver}://{user}:{password}@{host}:{port}/{db_name}'
############################################################
engine = create_engine(cnx)
table = 'test_table'
col = 'test_col'
with engine.begin() as con:
# this would work here instead of creating a new engine with a new link
# con.execute(f"USE {db_name}")
con.execute(f"CREATE TABLE {table} ({col} CHAR(1));")
# insert into database
import pandas as pd
df = pd.DataFrame({col : ['a','b','c']})
with engine.begin() as con:
# this has no effect here
# con.execute(f"USE {db_name}")
df.to_sql(
name= table,
if_exists='append',
con=con,
############################################################
# or pass it as a schema vvvv - HERE - vvvv
#schema=db_name,
############################################################
index=False
)```
Run Code Online (Sandbox Code Playgroud)
使用 python 版本3.8.13、sqlalchemy1.4.32和 pandas进行了测试1.4.2。同样的问题可能出现在这里和这里。
| 归档时间: |
|
| 查看次数: |
2965 次 |
| 最近记录: |