Browse Source

更换mysql连接方式,使用orm框架sqlalchemy

master
zhangshu 6 months ago
parent
commit
c7610e110c
  1. 25
      entity/Channel.py
  2. 16
      init_channel.py

25
entity/Channel.py

@ -0,0 +1,25 @@
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
# 创建一个基类
Base = declarative_base()
class Channel(Base):
__tablename__ = 'Channel'
id = Column(Integer, primary_key=True, autoincrement=True)
channelId = Column(String(255), nullable=False)
channelTitle = Column(String(255), nullable=False)
channelLanguage = Column(String(255), nullable=False)
channelReptileTime = Column(String(255), nullable=True)
region = Column(String(255), nullable=True)
# 如果需要,可以在这里定义其他方法或属性
# 注意:这里只是定义了模型,并没有与数据库建立连接。
# 若要与数据库建立连接并创建表,你需要使用`create_engine`来创建一个数据库引擎,
# 然后使用`Base.metadata.create_all(engine)`来创建表。
# 例如:
# engine = create_engine('mysql+pymysql://user:password@localhost/your_database_name', echo=True)
# Base.metadata.create_all(engine)

16
init_channel.py

@ -3,8 +3,7 @@ from bs4 import BeautifulSoup as bs
from urllib.request import urlopen, Request from urllib.request import urlopen, Request
import json import json
import Contant import Contant
import mysql.connector from sqlalchemy import create_engine
from mysql.connector import Error
# py .\init.py --db=../db/youtube_prod.db --logDir=./logs # py .\init.py --db=../db/youtube_prod.db --logDir=./logs
if __name__ == "__main__": if __name__ == "__main__":
@ -26,15 +25,4 @@ if __name__ == "__main__":
dbDatabase = data['mysql']['database'] dbDatabase = data['mysql']['database']
Logger.info("尝试连接mysql host:'{}' port:'{}' username:'{}' password:'{}' database:'{}'", Logger.info("尝试连接mysql host:'{}' port:'{}' username:'{}' password:'{}' database:'{}'",
dbHost, dbPort, dbUserName, dbPassword, dbDatabase) dbHost, dbPort, dbUserName, dbPassword, dbDatabase)
Contant.connection = None engine = create_engine(f'mysql+mysqlconnector://{dbUserName}:{dbPassword}@{dbHost}:{dbPort}/{dbDatabase}')
try:
Contant.connection = mysql.connector.connect(
host=dbHost,
port=dbPort,
user=dbUserName,
passwd=dbPassword,
database=dbDatabase
)
Logger.info("连接数据库成功")
except Error as e:
Logger.error(f"The error '{e}' occurred")

Loading…
Cancel
Save