• python操作mysql


    python3中操作mysql数据需要安装一个第三方模块,pymysql,使用pip install pymysql安装即可.

    在python2中是MySQLdb模块,在python3中没有MySQLdb模块了,所以使用pymysql。

    import pymysql
        # 创建连接,指定数据库的ip地址,账号、密码、端口号、要操作的数据库、字符集
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='data',charset='utf8')
        # 创建游标
        cursor = conn.cursor()
        # 执行SQL,并返回收影响行数
        effect_row = cursor.execute("update students set name = 'niuhy' where id = 1;")
        # 执行SQL,并返回受影响行数
        #effect_row = cursor.execute("update students set name = 'niuhy' where id = %s;", (1,))
        # 执行SQL,并返回受影响行数
        effect_row = cursor.executemany("insert into students (name,age) values (%s,%s); ", [("andashu",18),("12345",20)])
        #执行select语句
        cursor.execute("select * from students;")
        #获取查询结果的第一条数据,返回的是一个元组
        row_1 = cursor.fetchone()
        # 获取前n行数据
        row_2 = cursor.fetchmany(3)
        # 获取所有数据
        row_3 = cursor.fetchall()
        # 提交,不然无法保存新建或者修改的数据
        conn.commit()
        # 获取最新自增ID
        new_id = cursor.lastrowid    
        print(new_id)
        # 关闭游标
        cursor.close()
        # 关闭连接
        conn.close()
        上面的操作,获取到的返回结果都是元组,如果想获取到的结果是一个字典类型的话,可以使用下面这样的操作
     
        import pymysql
        # 创建连接,指定数据库的ip地址,账号、密码、端口号、要操作的数据库、字符集
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='data',charset='utf8')
        # 创建游标
        cursor = conn.cursor()
        
        cursor = coon.cursor(cursor=pymysql.cursors.DictCursor)#需要指定游标的类型,字典类型
        # 执行SQL
        cursor.execute("select * from user;")
        #获取返回结果,这个时候返回结果是一个字典
        res = cursor.fetchone()#返回一条数据,如果结果是多条的话
        print(res)
        res2 = cursor.fetchall()#所有的数据一起返回
  • 相关阅读:
    选择筛选
    添加标签2 jquery 和JS
    最全的常用正则表达式大全
    Javascript和ECMAScript二三事
    display:none和visibility: hidden二三事
    说人话
    渐进增强和优雅降级
    css的优先级以及!important的使用
    解决VS如何同时打开两个工程(xp和win7)
    jQuery验证控件jquery.validate.js使用说明+中文API
  • 原文地址:https://www.cnblogs.com/lazy-cat-home/p/7101907.html
Copyright © 2020-2023  润新知