zoukankan      html  css  js  c++  java
  • 寒假学习进度-6(Python连接MySQL数据库)

    Python连接mysql和操作

    软件:pycharm

    开始在pycharm下面的Terminal中安装mysql时提醒pip版本不够,所以需要先升级一下pip

    python -m pip install --upgrade pip

    升级完pip之后就可以下载mysql

    pip install mysql

    下载完成后在setting中查看

    进行代码测试

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    db =MySQLdb.connect("localhost","root","liu123","test",charset='utf8')
    cursor=db.cursor()
    cursor.execute("SELECT VERSION()")
    data=cursor.fetchone()
    print ("Database version : %s" % data)
    db.colse()
    Database version : 5.7.10-log

    插入

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    db =MySQLdb.connect("localhost","root","liu123","test",charset='utf8')
    cursor=db.cursor()
    sql="insert into admin(account,passwd) values ('abc','123456789')"
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
    db.close()

    查找

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    db =MySQLdb.connect("localhost","root","liu123","test",charset='utf8')
    cursor=db.cursor()
    sql="select * from admin"
    try:
        cursor.execute(sql)
        results=cursor.fetchall()
        for row in results:
            account=row[0]
            password=row[1]
            print("account=%s,password=%s" % (account,password))
    except:
        print("Error:unable to fetch data")
    db.close()

    更新

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    db =MySQLdb.connect("localhost","root","liu123","test",charset='utf8')
    cursor=db.cursor()
    sql="update admin set passwd = 987654321 where account ='root'"
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
    db.close()

    删除

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    db =MySQLdb.connect("localhost","root","liu123","test",charset='utf8')
    cursor=db.cursor()
    sql="delete from admin where account ='root'"
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
    db.close()
  • 相关阅读:
    python爬虫系列之爬取多页gif图像
    python连续爬取多个网页的图片分别保存到不同的文件夹
    python多线程同步
    python多线程简单例子
    python定时器爬取豆瓣音乐Top榜歌名
    python模拟Get请求保存网易歌曲的url
    python使用get在百度搜索并保存第一页搜索结果
    python爬取某个网页的图片-如百度贴吧
    完全揭秘log file sync等待事件-转自itpub
    两表关联更新
  • 原文地址:https://www.cnblogs.com/liujinxin123/p/12254784.html
Copyright © 2011-2022 走看看