用于进行Mysql操作,DB上传。
需要安装:pip install pymysql
import pymysql
class DB(object):
'''import pymysql'''
def help(self):
help = '''Before program: You need install lib(pip install pymysql), and then import pymysql.
Create Schema: CREATE SCHEMA `mydb` DEFAULT CHARACTER SET utf8 ;
Create Table: CREATE TABLE `mydb`.`123` (`id` INT NOT NULL, `Name` VARCHAR(45) NULL, `Money` VARCHAR(45) NULL, PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
'''
print(help)
return help
def __init__(self):
config = INI_File()
config.Ini('.\cfg\config.ini')
self.db_handles = None
self.cursor = None
self.host = config.Read('DB','IP')
self.port = config.Read('DB', 'port')
self.user = config.Read('DB', 'user')
self.password = config.Read('DB', 'password')
self.db = config.Read('DB', 'db')
def connect(self):
try:
self.db_handles = pymysql.Connect(host=self.host,
port=int(self.port),
user=self.user,
password=self.password,
db=self.db,
charset='utf8')
self.cursor = self.db_handles.cursor()
log = f'Connect Pass, {self.host,self.port,self.user,self.password,self.db,"utf8"}.'
except Exception as e:
log = f'Connect Fail, {self.host,self.port,self.user,self.password,self.db,"utf8"}.\r\n{e.__str__()}'
return log
def upload(self,data):
'''insert or update'''
self.cursor.execute(data) # 运行语句,使用pymysql.connect.curssor handle来操作。
self.db_handles.commit() # 上传DB语句,使用pymysql.connect handle来操作。
return self.cursor.fetchall()
pass # DB调试程序
d = DB()
print(d.connect())
print(d.upload('insert into cssc (SERIAL_NUMBER, MANUFACTURER, ASSEMBLY_DATE) values ("S2", "8563", "2024-01-23 10:19:42")'))
print(d.upload("""SELECT * FROM daredevil_elektra.cssc LIMIT 0, 1000"""))