Python中使用PyMySQL

Python中使用PyMySQL

1.项目中使用PyMySQL一些案例

建立一个config.py 用于存储配置文件

Python中使用PyMySQL

2.测试

##获取数据
from config import ctf

'''connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接
'''

'''cursor 对象支持的方法
execute(op)     执行一个数据库的查询命令
fetchone()      取得结果集的下一行
fetchmany(size) 获得结果记得下几行
fetchall()      获取结果集中的所有行
rowcount()      获取数据条数或者影响条数
close()         关闭游标
'''


def get_data():
    try:
        with ctf.con_localhost.cursor() as cursor:
            # 创建一个新的sql语句
            sql = "insert into web_sys_user(username, tel, password, oper) values ('%s','%s','%s','%s')"
            params = (1, 2, 3, 4)
            cursor.execute(sql, params)
            print('成功插入', cursor.rowcount, '条数据')
            ctf.con_localhost.commit()

        with ctf.con_localhost.cursor() as cursor:
            sql = "select * from web_sys_user"
            cursor.execute(sql)
            print('成功查询', cursor.rowcount, '条数据')
            ctf.con_localhost.commit()

    finally:
        # 关闭连接
        ctf.con_localhost.close()
        # 关闭游标
        ctf.con_localhost.cursor().close()


if __name__ == '__main__':
    get_data()

3.结果集

Python中使用PyMySQL