欢迎您光临本站
首页 > Python > 正文
李蓝猫头像
李蓝猫

2021-07-11

评论者
Python
14 0

pymysql是python连接mysql数据库的一个主流插件,用来实现数据库的CURD操作

github地址: https://github.com/PyMySQL/PyMySQL
安装方式:  pip install PyMySQL
文档地址:  https://pymysql.readthedocs.io/en/latest/


代码示例

import pymysql.cursors
 
# 连接数据库
connection = pymysql.connect(host='localhost',
                        user='root',
                        password='123456',
                        db='test',
                        charset='utf8')
#处理异常
try:
    with connection.cursor() as cursor:
        # 插入一条新纪录  VALUES 内参数用%s表示 execute()内为%s对应参数
        sql = "INSERT INTO `pre_url` (`title`, `url`) VALUES (%s, %s)"
        cursor.execute(sql, ('6666655', '56789'))
 
    #连接不会自动提交 所以你需要commit来提交你得改变
    connection.commit()
 
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`,`title`,`url` FROM `pre_url` "
        #查询条数
        #一条语句对应一条数据执行 用excute 但要是一条语句执行多个数据就要用executemany
        count = cursor.execute(sql)
        print(count)
        #查询所有
        #result = cursor.fetchall()
        #查询指定条数
        result = cursor.fetchmany(size=2)
        print(result)
finally:
    #无论何种情况都要释放资源关闭数据库
    connection.close()


版权声明:本站所提供的文章、图片等内容均为用户发布或互联网整理而来,仅供学习参考,如有侵犯您的版权,请联系我们客服人员删除。

294

精彩推荐

暂无评论

文明用语