安装平台:windows、py3.x
pymysql是python中操作mysql的模块
#运行pip3 install pymysql命令安装
mysql版本:mysql-installer-community-8.0.12.0
基本命令
创建数据库 create database student;
使用数据库 use student;
显示所有表 show tables;
import pymysql
#1、创建数据库连接对象
connect = pymysql.connect(
# host:表示主机地址
# 127.0.0.1 本机ip
# 172.16.21.41 局域网ip
# localhost (local:本地 host:主机 合在一起为本地主机的意思)
# host表示mysql安装的地址
host=“127.0.0.1”,
user=“root”,
passwd=“123456”,
# mysql默认的端口号是3306
port=3306,
# 数据库名称
db=“student”
)
#2、创建游标,用于操作表
cursor = connect.cursor()
3、创建表
create_table = “create table if not exists stu (name varchar(30), age integer, phone varchar(11))”
cursor.execute(create_table)
#4、表的增、删、改、查
#增加
insert_table = “insert into stu (name,age,phone) values (‘张三’, 19, ‘13332001256’)”
cursor.execute(insert_table)
删除
delete_table = “delete from stu where name=‘张三’”
cursor.execute(delete_table)
修改
update_table = “update stu set age = 20 where id < 10”
cursor.execute(update_table)
查询
select_table = “select * from stu”
res = cursor.execute(select_table)
s = res.fetchone()
print(s)
ss = res.fetchall()
print(ss)
5、提交sql语句
connect.commit()
6、关闭游标、数据库
cursor.close()
connect.close()