mysql 如何在Python中使用sqlalchemy正确关闭和打开与两个不同主机的连接?

agxfikkp  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(174)

基本上,我不需要做任何花哨的事情。我只是尝试远程连接到MySQL数据库,将其拉入pandas框架中,做一些工作,然后我想将其作为表输出,但这一次,到本地数据库,全部使用MySQL格式化并使用Python。我对SQLAlchemy的会话,引擎,连接等感到非常困惑,坦率地说,我不确定我是否真的需要任何深层次的功能。当我过去用R做这件事时,它只是一个简单的问题,显式地关闭旧连接,然后用一个新连接做同样的事情。
然而,据我所知,没有专门的方法来关闭我能够理解的连接(例如this link超出了我的理解范围)。
我真的只需要一个pandas.read_sql()命令来检索一个表,一个to.sql()命令来写这个表。
但这是一个单一的数据库。我在哪里放一些断开连接的语句?“引擎”可以同时运行吗?我应该使用游标,或执行,或某种其他类型的接口与SQL?

  1. hostname = "remote.server.com"
  2. username = "user"
  3. password = "pass"
  4. database = "mydb"
  5. engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}".format(host=hostname, db=database, user=username, pw=password))
  6. getcommand = "SELECT * FROM table"
  7. df = pd.read_sql(getcommand, engine)
  8. #work with the df
  9. df.to_sql(name="dbname", con=engine, if_exists="replace", index=False)

字符串

ddhy6vgd

ddhy6vgd1#

我相信你需要在打开本地连接的同时打开远程连接,因为你可能在用pandas写作的同时还在阅读。
类似这样的东西应该可以工作。我认为把你的sql字符串也 Package 在text中可能会更好。

  1. #... define remote and local connection variables
  2. # other imports
  3. from sqlalchemy.sql import text
  4. remote_engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}".format(host=remote_hostname, db=remote_database, user=remote_username, pw=remote_password))
  5. local_engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}".format(host=local_hostname, db=local_database, user=local_username, pw=local_password))
  6. getcommand = text("SELECT * FROM table")
  7. # remote (SA) connection returned to engine(pool) after end of with block
  8. with remote_engine.connect() as remote_conn:
  9. df = pd.read_sql(getcommand, remote_conn)
  10. # local (SA) connection returned to engine(pool) after end of with block
  11. # begin will cause transaction to automatically commit unless
  12. # an exception occurs.
  13. with local_engine.connect() as local_conn, local_conn.begin():
  14. df.to_sql(name="dbname", con=local_conn, if_exists="replace", index=False)
  15. # db api connections closed when script ends when everything goes out of scope and is garbage collected

字符串

展开查看全部

相关问题