• python3与mysql交互


    1.安装pymysql模块

    pip3 install pymysql3

    2.pymysql的简单使用:

    # /usr/bin/env python3
    import pymysql
    
    
    class Mysql(object):
        def __init__(self):
            try:
                self.conn = pymysql.connect(
                    host='127.0.0.1',
                    port=3306,
                    user='root',
                    passwd='mysql',
                    db='testdb',
                    charset='utf8'
                )
            except Exception as e:
                print(e)
            else:
                print('连接成功')
                self.cur = self.conn.cursor()
    
        def create_table(self):
            sql = 'create table testtb(id int, name varchar(10),age int)'
            res = self.cur.execute(sql)
            print(res)
    
        def close(self):
            self.cur.close()
            self.conn.close()
    
        def add(self):  # 增
            sql = 'insert into testtb values(1,"Tom",18),(2,"Jerry",16),(3,"Hank",24)'
            res = self.cur.execute(sql)
            if res:
                self.conn.commit()
            else:
                self.conn.rollback()
            print(res)
    
        def rem(self):  # 删
            sql = 'delete from testtb where id=1'
            res = self.cur.execute(sql)
            if res:
                self.conn.commit()
            else:
                self.conn.rollback()
            print(res)
    
        def mod(self):  # 改
            sql = 'update testtb set name="Tom Ding" where id=2'
            res = self.cur.execute(sql)
            if res:
                self.conn.commit()
            else:
                self.conn.rollback()
            print(res)
    
        def show(self):  # 查
            sql = 'select * from testtb'
            self.cur.execute(sql)
            res = self.cur.fetchall()
            for i in res:
                print(i)
    
    if __name__ == "__main__":
        mysql = Mysql()
        mysql.create_table()
        mysql.add()
        mysql.mod()
        mysql.rem()
        mysql.show()
        mysql.close()
  • 相关阅读:
    取字符串前缀
    分解质因数
    git 常用命令
    微信 iphone端 audio 播放问题
    git入门:创建合并分支 解决冲突 分支管理策略
    git入门:远程仓库 github篇
    git入门:撤销修改 删除文件
    git入门: 工作区暂存区 以及 管理修改
    函数柯里化实现
    转载:深度工作:充分使用每一份脑力
  • 原文地址:https://www.cnblogs.com/yunlongaimeng/p/10438340.html
Copyright © 2020-2023  润新知