zoukankan      html  css  js  c++  java
  • 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()#所有的数据一起返回
  • 相关阅读:
    民族、学历学位、所学专业、、专业技术职务 对应表
    Spring企业业务快速开发平台应该具备的基本框架
    winform中与asp.net中的 TreeView节点处理对比
    GB85611988《专业技术职务代码》
    ASP.NET获取文件名,后缀名
    各种国家标准代码表
    同样的门通向同样的结果要想得到没有的就要做不同的事
    哈佛MBA生是这样找工作的
    富爸爸,穷爸爸 总结财务自由
    WebSite和Web Application\网站与Web项目的区别
  • 原文地址:https://www.cnblogs.com/lazy-cat-home/p/7101907.html
Copyright © 2011-2022 走看看