zoukankan      html  css  js  c++  java
  • Python对MySql增删改查

    pip install pymysql

    import pymysql
    
    db_config = {
        'host': '127.0.0.1(ip)',
        'port': 3306,
        'user': '账号',
        'password': '密码',
        'db': '数据库名',
        'charset': 'utf8'
    }
    
    # 建立连接
    conn = pymysql.connect(**db_config)
    
    #   连接是不能操作数据库的,需要生成游标来操作
    #   获取cursor
    cur = conn.cursor()
    

    基本使用:insert 、 delete 、 update 、 select


    try

    try:
        #   增(insert into values)
        #   指定字段
        # sql_insert = "insert into temp(name,age) values ('jy',11),('nh',22),('fe',33)"
        #   全字段
        # sql_insert = "insert into temp values (1, 'bk', 44, 'f')"
        #   执行sql语句
        # cur.execute(sql_insert)
    
    
        #   删(delete from where)
        #   删除表中满足条件的数据
        # sql_delete = "delete from temp where id > 5"
        #   删除表中所有数据
        # sql_delete = "delete from temp"
        #   执行sql语句
        # cur.execute(sql_delete)
    
    
        #   改(update set where)
        #   修改满足条件的多个字段
        # sql_update = "update temp set id = 0, sex = 'm' where name = 'jy' "
        #   修改满足条件的单个字段
        # sql_update = "update temp set sex = 'f' where id is null"
        #   修改所有数据
        # sql_update = "update temp set sex = 'noth'"
        #   执行sql语句
        # cur.execute(sql_update)
    
    
        #   查(select from where)
        sql_select = "select * from temp"
        #   执行SQL命令,然后返回生效行数
        #   SQL语句都是通过execute方法执行
        num = cur.execute(sql_select)
        # print(num)
    
        #   获取结果
        #   取出所有        fetchall()
        for i in cur.fetchall():
            print(i)
        #   取出一条        fetchaone()
        # print(cur.fetchone())
        #   取出具体几条    fetchamany(num)
        # print(cur.fetchmany(5))
    
    
        #   提交事务
        conn.commit()
    

    except

    except Exception as message:
        #   打印异常
        print(message)
        #   发生异常,回滚事务
        conn.rollback()
    

    finally

    finally:
        #   关闭游标
        cur.close()
        #   关闭连接
        conn.close()
    




  • 相关阅读:
    《团队-爬取豆瓣Top250-团队一阶段互评》
    团队-爬虫豆瓣top250项目-开发文档
    结对总结
    课后作业-阅读任务-阅读提问-2
    2017-10-06-构建之法:现代软件工程-阅读笔记
    结对-结对编项目贪吃蛇-开发过程
    团队-爬取豆瓣电影TOP250-开发环境搭建过程
    个人-GIT使用方法
    课后作业-阅读任务-阅读提问-1
    课后作业-阅读任务-阅读笔记-1
  • 原文地址:https://www.cnblogs.com/jiyu-hlzy/p/11972063.html
Copyright © 2011-2022 走看看