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()#所有的数据一起返回
  • 相关阅读:
    Good Bye 2014 B. New Year Permutation(floyd )
    hdu 5147 Sequence II (树状数组 求逆序数)
    POJ 1696 Space Ant (极角排序)
    POJ 2398 Toy Storage (叉积判断点和线段的关系)
    hdu 2897 邂逅明下 (简单巴什博弈)
    poj 1410 Intersection (判断线段与矩形相交 判线段相交)
    HDU 3400 Line belt (三分嵌套)
    Codeforces Round #279 (Div. 2) C. Hacking Cypher (大数取余)
    Codeforces Round #179 (Div. 2) B. Yaroslav and Two Strings (容斥原理)
    hdu 1576 A/B (求逆元)
  • 原文地址:https://www.cnblogs.com/lazy-cat-home/p/7101907.html
Copyright © 2011-2022 走看看