[Python_6] Python 配置 MySQL 访问


 0. 说明

  Python 访问 MySQL 数据库,需要安装 MySQL 的 Python 插件。

 

 


1. 安装 MySQL 插件

pip install PyMySQL

 


2. 编写代码

# -*-coding:utf-8-*-import pymysql""" Python 访问 MySQL 数据库"""""" 创建表的命令create table t1(id int,name varchar(20),age int);"""# 连接到数据库 ,注意使用127.0.0.1conn = pymysql.Connect("127.0.0.1", "root", "123456", "python")# 得到游标cur = conn.cursor()# 执行语句# cur.execute("select version()")# 提取第一条记录# result = cur.fetchone()# print(result)# 插入记录# cur.execute("insert into t1(id ,name ,age) values(2 ,‘amy‘ , 23)")# 查询 t1表 所有记录print("=================")cur.execute("select * from t1")results_list = cur.fetchall()for r in results_list: id = r[0] name = r[1] age = r[2] print("%d/%s/%d\r\n" % (id, name, age), )# 删除记录# cur.execute("delete from t1 where id >= 1000")conn.commit()cur.close()

 

 


 

相关文章