Python中使用PyMySQL

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

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

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.结果集测试

相关文章
相关标签/搜索