SQL基础语法回忆
show DATABASES;
use world;-- SELECT DATABASES();show TABLES;
CREATE TABLE Student(id int,name VARCHAR(10),age int,gender VARCHAR(5)
);
删除表
# 删除表
DROP TABLE Student;
插入操作
insert into student(id) VALUES(1),(2),(3);insert into student (id,name,age) VALUES (4 , 'jay',30),(5,'zhou',20);
删除数据
DELETE FROM student WHERE id = 1;
更新操作
UPDATE student SET name = 'zhao' where id = 2;update student set age = 18 where name = 'zhao';update student set age = 36, name = 'li' WHERE id = 3;
查询
select * from student;
条件查询
select * from student WHERE age >= 20;
分组聚合
-- 分组聚合
select avg(age),gender from student GROUP BY gender;
排序分页
-- 排序分页
select * from student where age >20 ORDER BY age asc;
跳过第一条,输出后面三条
SELECT * FROM student LIMIT 1,3;
输出前两条
SELECT * FROM student LIMIT 2;
在python中,使用第三方库:pymysql实现对mysql的操作
1、导包
"""
python pymysql库操作数据库
"""from pymysql import Connection
2、构建到MySQL数据库的链接
# 构建到MySQL数据库的链接
conn = Connection(host="localhost",port=3306,user="root",password="****",autocommit=False, # 自动提交确认
)
验证是否链接成功,打印mysql版本号
print(conn.get_server_info())
3、获取游标对象(非查询)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("test") # 选择数据库,test or world
4、执行非查询SQL
cursor.execute("create table test_pymysql_2(id int,name varchar(10),gender varchar(5),age int);")
5、关闭链接
conn.close()
3、获取游标对象(查询)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("world") # 选择数据库,test or world
4、执行查询SQL,需获取结果语句fetchall() ,以元组形式返回
# 执行查询SQL,需获取结果语句
cursor.execute("select * from student")
results = cursor.fetchall() # 获取查询结果
print(type(results))
print(results)for r in results:print(r)
5、关闭链接
conn.close()
3、获取游标对象(插入)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("test") # 选择数据库,test or world
4、执行插入数据操作,必须通过commit确认
# 执行插入数据操作,必须通过commit确认
cursor.execute("insert into test_pymysql_2 values (2,'zhao','男',18),(3,'li','男', 36),(4,'jay','女',30),(5,'zhou','女',20);")
conn.commit() # 确认
5、关闭链接
conn.close()