• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

关闭

返回栏目

关闭

返回python栏目

103 - 第三方库 - 操作MySQL存储 - PyMySQL - 写成类

作者:

贺及楼

成为作者

更新日期:2024-05-30 11:52:10

PyMySQL

使用连接数据库 pymysql库 例子

  1. import pymysql
  2. from sqlalchemy import create_engine
  3. class Mysql():
  4. def __init__(self):
  5. self.ip = "127.0.0.1"
  6. self.port = "3306"
  7. self.port2 = 3306
  8. self.username = "root"
  9. self.secret = "xxxxxx"
  10. self.dbname = "dbname"
  11. self.tablename = "tablename"
  12. def connect(self):
  13. url = 'mysql+pymysql://'+self.username+':'+self.secret+'@'+self.ip+':'+self.port+'/'+self.dbname+'?charset=utf8mb4'
  14. print(url)
  15. connect = create_engine(url)
  16. return connect
  17. def connect2(self):
  18. db = pymysql.connect(host=self.ip, user=self.username, password=self.secret, port=self.port2, database=self.dbname)
  19. cursor = db.cursor() # 获得指针
  20. return cursor
  21. def select(self):
  22. cursor = self.connect2()
  23. sql = 'select * from dbname.tablename;'
  24. cursor.execute(sql) # 执行
  25. return cursor