[DATABASE] # 数据库配置 host = tmysql.***.com username = kevin password =****** port = 3306 database = HT_IMDB
import configparser from pathlib import Path class ReadConfig(): def __init__(self): configDir = Path.cwd().parent.joinpath("config.ini") # 配置文件地址 self.cf = configparser.ConfigParser() self.cf.read(configDir) def getHTTPValue(self, name): value = self.cf.get("HTTP", name) return value def getDBValue(self, name): value = self.cf.get("DATABASE", name) return value
import pymysql import readConfig localReadConfig = readConfig.ReadConfig() class myDB: def __init__(self): self.host = localReadConfig.getDBValue("host") self.username = localReadConfig.getDBValue("username") self.password = localReadConfig.getDBValue("password") self.port = int(localReadConfig.getDBValue("port")) self.database = localReadConfig.getDBValue("database") def connect_mysql(self): #连接数据库 conn = pymysql.connect(host=self.host,port=self.port,user=self.username,password=self.password,database=self.database) #使用cursor()方法创建一个游标对象 cursor = conn.cursor() #使用execute()方法执行SQL语句 cursor.execute("SELECT * FROM HT_VIRTUAL_GIFT") #使用fetall()获取全部数据 data = cursor.fetchall() cursor.close() conn.close() return data test = myDB() data = test.connect_mysql() print(data)