• python操作MySQL


    python操作MySQL

    2019-08-23

    使用pymysql模块进行MySQL的操作,主要分为下面几个步骤,不同的操作会有些许不同,但答题符合下面的步骤。

    具体对数据库表进行增删改查会有不同的操作,具体见2,3,4节。

    1操作步骤

    1.连接

    2.创建游标

    3.执行SQL语句

    4.关闭游标

    5.关闭SQL连接

    #导入模块
    import pymysql
    
    #连接MySQL
    conn = pymysql.connect(host="localhost",user="root",password="",database="db1")
    
    #创建游标
    cursor = conn.cursor()
    
    #执行命令
    sql = "show tables"
    cursor.execute(sql)
    
    #关闭游标
    cursor.close()
    
    #关闭连接
    conn.close()
    View Code

    2.新建/删除数据库表

    符合基本步骤的操作。

    #导入模块
    import pymysql
    
    #连接MySQL
    conn = pymysql.connect(host="localhost",user="root",password="",database="db2")
    
    #创建游标
    cursor = conn.cursor()
    
    #删除test1表
    sql = "drop table test1"
    cursor.execute(sql)
    #创建test2表
    sql = '''create table test2(
            id int auto_increment primary key,
            name char(20),
            part int not null
            )
    '''
    cursor.execute(sql)
    
    #关闭游标
    cursor.close()
    
    #关闭连接
    conn.close()
    View Code

    3.数据库表内容修改操作

    对数据库表内的内容进行修改操作后,需要数据进行提交,才能使之写入到本地硬盘中:

     3.1插入操作

    sql = '''insert into test2(name,part) values("doom",301)'''
    cursor.execute(sql)
    #提交/上传
    conn.commit()
    
    #也可以插入多条
    sql = "insert into test2(name,part) values(%s,%s)"
    cursor.executemany(sql,[("jugg",201),("pom",101),("volock",301)])
    conn.commit()
    View Code

    3.2修改操作

    #更新数据
    sql = "update test2 set part=501 where part=101"
    cursor.execute(sql)
    conn.commit()

    3.3删除操作

    #删除id大于6的数据
    sql = "delete from test2 where id>6"
    cursor.execute(sql)
    #提交/上传
    conn.commit()

    4查询操作

    #查询数据表内容
    sql = "select * from test2"
    cursor.execute(sql)
    #取出第一条数据
    result = cursor.fetchone()
    #取出3条数据
    result = cursor.fetchmany(3)
    #取出所有数据
    result = cursor.fetchall()

    其中fetchone函数是一条一条取数据,直到所有数据取完,fetchmany(n)是一下取出n条数据,fetchall是一下将所有数据取出。

  • 相关阅读:
    轮播图案例
    如何使用google等一系列搜索引擎?
    开源项目weiciyuan运行前gradle调试过程记录
    onRetainNonConfigurationInstance方法状态保存
    关于stickybroadcast
    关于Bundle对象的思考
    android中finish和system.exit方法退出的区别
    关于RAW 和 ASSEST文件夹的差异
    图片缓存核心类LruCache
    Android常用开源库集合【持续更新】
  • 原文地址:https://www.cnblogs.com/sienbo/p/11400237.html
Copyright © 2020-2023  润新知