[分章:代码知识]python Mysql操作

发布时间:2024年01月24日

pymysql MySQL操作

作用:

用于进行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"""))

文章来源:https://blog.csdn.net/weixin_42645007/article/details/135772797
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。