06: Pymysql

1.1 Pymysql安装与简介

  1、安装

      pip3 install pymysql

  2、介绍(支持python3)

      1. pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同

      2. 我们可以使用pymysql使用原生sql语句操作数据库

  3、使用root连接时必须先对root用户授权不然会报错

      mysql> grant all on *.* to 'root'@'%' identified by '1';
      mysql> flush privileges;

1.2 pymysql基本使用

  1、原生SQL语句创建数据库和表

      create table student(
        id int auto_increment,
        name char(32) not null,
        age int not null,
        register_data date not null,
        primary key (id))
        engine=InnoDB
        ;

  2、pymysql执行MySQL增删改查命令

import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='1', db='tomdb')
# 创建游标(光标的位置)上面仅仅是建立一个socket,这里才是建立一个实例
cursor = conn.cursor()
#1 向tomdb数据库的student表中插入三条数据
data = [
    ('zhaoliu',98,"2017-03-01"),
    ('tom',98,"2017-03-01"),
    ('jack',98,"2017-03-01"),
]
cursor.executemany("insert into student (name,age,register_data) values(%s,%s,%s)",data)

#2 执行SQL,并返回收影响行数,和结果
effect_row = cursor.execute("select * from student")
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
print(effect_row)               #打印select查询到多少条语句
print(cursor.fetchone())        #打印出查询到的一条语句
print(cursor.fetchall())        #将剩下所有未打印的条目打印出来
原文地址:https://www.cnblogs.com/xiaonq/p/8430522.html