Python Pymysql

Installation and Introduction 1.1 Pymysql

1. Install

pip3 install pymysql

2, introduction (support python3)

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

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

3, the use of root connection must be or will be error for the root user authorization

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

mysql> flush privileges;

1.2 pymysql basic use

1, native SQL statements to create databases and tables

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 perform CRUD MySQL command


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())        #将剩下所有未打印的条目打印出来

Guess you like

Origin www.cnblogs.com/xinzaiyuan/p/12381146.html