使用PyMySQL操作sql数据库

PyMySQL是Python3.x版本中用于连接MySQL服务器的一个库,Python2中使用mysqldb。PyMySQL库安装命令:

pip install pymysql

一、pymysql的主要方法

pymysql.connect()参数说明:(连接数据库时需要设置的参数)
host(str): MySQL服务器地址
port(int): MySQL服务器的端口号
user(str): 数据库登录用户名
passwd(str): 数据库登录密码
db(str): 数据库名称
charset(str): 连接编码

connect()对象支持的方法:
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接

cursor对象支持的方法
execute(op) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchhall() 获取结果集中的所有行
rowcount() 返回数据条数或影响行数
close() 关闭游标对象

二、数据库基本操作案例

# -*- coding:utf-8 -*-
"""
__project_ = 'p_pymysql'
__file_name__ = 'p_pymysql'
__author__ = 'xbxia'
__time__ = '2020/3/1 16:30'
__product_name = PyCharm
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃        ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃ 永无BUG!   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

import pymysql.cursors

# 1、连接数据库
conn = pymysql.connect(
    host='172.16.22.132',
    port=63306,
    user='root',
    passwd='sa',
    db='student',
    charset='utf8'
)

#创建一个可以执行SQL语句的光标对象
cursor = conn.cursor()      #执行完毕返回的结果集默认以元组显示
#cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)   #作为字典返回的游标

# 定义要执行的SQL语句
# 2、建库
# sql_database = """
# create database student;
# """
# cursor.execute(sql_database)
# 3、建表
# sql_table_student = """
# create table student(
# id int(12) not null PRIMARY key,
# name varchar(12),
# sex varchar(12),
# class_id varchar(12),
# school_id varchar(12),
# address varchar(12),
# create_date datetime,
# update_date datetime
# )DEFAULT CHARSET=utf8;
# """
# cursor.execute(sql_table_student)
#
# sql_table_grade = """
# create table grade(
# id int(12) not null PRIMARY key,
# grade varchar(12)
# )DEFAULT CHARSET=utf8;
# """
# cursor.execute(sql_table_grade)

# 4、插入数据
# sql_insert_grade = """
# insert into grade(id,grade) values(1,'高一年级');
# """
# cursor.execute(sql_insert_grade)

# 一次插入多条数据
# sql_insert_student = """
# insert into student(id,sex,create_date) values(1,'女',SYSDATE()),(2,'男',SYSDATE());
# """
# cursor.execute(sql_insert_student)

# 5、修改数据
# sql_update_student = "update student set sex='男/女';"
# cursor.execute(sql_update_student)
# 修改满足条件的数据记录
# sql_update_student = "update student set sex='女' where id=2;"
# cursor.execute(sql_update_student)

# 6、查询数据
sql_select_student = "select * from student;"
cursor.execute(sql_select_student)
# 查询所有数据,以默认元组形式返回,进行迭代处理
for i in cursor.fetchall():
    print(i)
print("共查询到:", cursor.rowcount, "条数据")
# 获取第一行数据
# result_1 = cursor.fetchone()
# print(result_1)
# 获取前n行数据
# result_3 = cursor.fetchmany(3)
# print(result_3)

# 7、删除表里满足条件的数据
# sql_delete_student = "delete from student where sex='男/女';"
# cursor.execute(sql_delete_student)

# 8、删表
# sql_drop_table = "drop table grade;"
# cursor.execute(sql_drop_table)

# 9、删库
# sql_drop_database = "drop database student;"
# cursor.execute(sql_drop_database)

conn.commit()     #提交,不然无法保存插入或修改的数据
cursor.close()    #关闭游标
conn.close()     #关闭连接
 
posted @ 2020-03-01 19:59  ReluStarry  阅读(654)  评论(0编辑  收藏  举报