Python3 PyMySQL 的使用

什么是 PyMySQL?

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

python中安装pymysql:

pip install pymysql

安装好pymysql后就可以进行操作了。但是要确认以下操作已提前完成:

首先已经创建好名字为test的数据库

2.开始正题,现在开始使用pymysql创建名字为table_1的表,

# -*- coding: utf-8 -*-
# @Time    : 2018/10/18 20:31
# @Author  : Hong_Liu
# @Email   : 2470937***@qq.com
# @File    : s2.py
# @Software: PyCharm


import pymysql

# 创建mysql数据库连接localhost为ip地址,root为了用户名,root为密码,连接到test数据库。
db = pymysql.connect('localhost','root','root','test')

# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()

# 使用sql语句
sql = """create table if not exists table_1(
            id int auto_increment primary key,
            name varchar(32)
            )"""
# 执行execute()方法生成table_1表
cursor.execute(sql)

# 关闭数据库连接
db.close()

在刚刚创建的table_1中插入数据:

# -*- coding: utf-8 -*-
# @Time    : 2018/10/18 20:46
# @Author  : Hong_Liu
# @Email   : 247093***@qq.com
# @File    : s3.py
# @Software: PyCharm


import pymysql

db = pymysql.connect('localhost','root','root','test')

# 使用cursor()方法创建一个游标
cursor = db.cursor()

# 编写插入sql语句

sql = """ insert into table_1(name) values('test1'),('test2')"""

try:
    # 执行sql插入数据
    cursor.execute(sql)

    # 保存数据到数据库
    db.commit()
    print('ok')


except:
    # 如果执行出错就回滚状态
    db.rollback()
    print('error')

# 最后依然是关闭数据库连接
db.close()

查询亦是如此。

从csdn搬家过来的可能没有图片,原地址https://blog.csdn.net/weixin_38091140
原文地址:https://www.cnblogs.com/Apy-0816/p/11100282.html