数据库操作

还是依赖第三方包,发现Python就这点好呢,需要的功能都是找个包完事,好无趣啊~

1安装

pip install PyMySQL

可以通过以下命令查看是够安装成功

pip show PyMySQL

2直接代码吧

import pymysql

if __name__ == "__main__":
    # 打开数据库连接,charset尽量加上
    db = pymysql.connect("localhost","root","root","test",charset='utf8mb4')
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # 方法一:插入数据
    # sql1 = """INSERT INTO `city` (`name`, `state`) VALUES
    # ('test1', 1),
    # ('test2', 1);"""
    # try:
    #     # 执行sql
    #     cursor.execute(sql1)
    #     # 提交事务
    #     db.commit()
    # except:
    #     # 异常回滚
    #     db.rollback()

    # 方法二:插入数据
    sql2 = """INSERT INTO `city` (`name`, `state`)  values (%s, %s)"""
    try:
        # 执行sql
        cursor.executemany(sql2,[('test3','1'),
                                 ('test4','1'),])
        # 提交事务
        db.commit()
    except:
        # 异常回滚
        db.rollback()

    # 查询:使用 execute()方法执行SQL 
    cursor.execute("SELECT * FROM city ORDER BY id DESC ")
    # 再使用fetchone()方法获取单条数据
    data = cursor.fetchone()

    print(data)

    # 关闭数据库
    db.close()

 

3其他

还有其他的功能,需要的时候自己查吓得了~

posted @ 2018-04-23 22:30  wbinbin  阅读(98)  评论(0)    收藏  举报