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()#所有的数据一起返回
  • 相关阅读:
    2.0 C++远征:隐藏
    1.0 C++远征:为什么继承
    15.0 C++远征:常指针和常引用
    14.0 C++远征:常对象成员和常成员函数
    13.0 C++远征:this指针
    12.0 C++远征:对象成员指针
    Sql语句
    斐波那契 递归 求某一个数
    WebAPI 和 WebService的区别
    获取用户IP
  • 原文地址:https://www.cnblogs.com/lazy-cat-home/p/7101907.html
Copyright © 2011-2022 走看看