インストールとはじめに1.1 Pymysql
インストール1.
pip3 install pymysql
図2に示すように、導入(支持のpython3)
1. pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同
2. 我们可以使用pymysql使用原生sql语句操作数据库
3、ルート接続の使用がなければなりませんか、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、CRUD MySQLのコマンドを実行しpymysql
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()) #将剩下所有未打印的条目打印出来