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()#所有的数据一起返回
  • 相关阅读:
    URL中#号(井号)的作用
    Sublime Text2 快捷键汇总
    Sublime Text2 使用及插件配置
    Sumblime Text 2 常用插件以及安装方法
    CSS禁止选择文本功能(兼容IE,火狐等浏览器)
    JavaScript 判断 URL
    纯真IP数据库格式读取方法(JAVA/PHP/Python)
    Sublime Text 2 性感无比的代码编辑器!程序员必备神器!跨平台支持Win/Mac/Linux
    base64:URL背景图片与web页面性能优化
    数独DFS实现
  • 原文地址:https://www.cnblogs.com/lazy-cat-home/p/7101907.html
Copyright © 2011-2022 走看看