SQL-Python

师从黑马程序员

数据库介绍

数据库就是存储数据的库

数据组织:库->表->数据

数据库和SQL的关系

MySQL的基础命令

SQL基础

SQL语言的分类

SQL的语法特征

DDL-库管理

sql 复制代码
show DATABASES;

use sys;

SELECT database();

CREATE DATABASE test CHARSET utf-8;

SHOW DATABASES;

-- drop DATABASE test01;

DDL-表管理

sql 复制代码
use students;

show TABLES;

CREATE TABLE student(
	id int,
	name VARCHAR(10),
	age int 
);

drop table student;

DML-数据操作

数据插入-INSERT

sql 复制代码
create table student(
	id int,
	name VARCHAR(10),
	age int
);

insert into student(id) VALUES(1),(2),(3);

# 等价于
-- insert into student(id) VALUES(1);
-- insert into student(id) VALUES(1);
-- insert into student(id) VALUES(1);
insert into student(id,name,age) VALUES(4,'周杰伦',31),(5,'领军解',33);

数据删除-DELETE

sql 复制代码
DELETE from student WHERE id =4;

数据更新-Update

sql 复制代码
UPDATE student set name ='张学友' where id ='5';

注:字符串的值,出现在SQL语句中,必须要用单引号

DQL-数据查询

基础数据查询

sql 复制代码
select id,name,age from student;

select * from student;

SELECT * from student where age>20;
select * from student where name ='张学友';

分组聚合

sql 复制代码
select id,avg(age) from student group by id;

-- 在非聚合函数中,GROUP BY 后出现什么,select 才能出现什么,但对像聚合函数avg()不适用

sql 复制代码
select id,avg(age),sum(age),min(age),max(age),count(*) from student group by id;

排序分页

结果排序

结果分页限制

sql 复制代码
select * from student where age >20 order by age ASC;
-- asc升序  de 降序
sql 复制代码
select * from student limit 5;
-- 只查询5条数据

SELECT * from student LIMIT 10,5;
-- 6跳过前10条数据,然后查询5条数据

-- 可以和其他语句结合
select age,count(*) from student where age>20 group by age ORDER BY age LIMIT 3;

Python操作MySQL语句

创建到MySQL的数据库链接

sql 复制代码
from pymysql import Connection


#构建到MySQL数据库的链接
conn=Connection(
    host="localhost",   #主机名
    port=3306,  #端口
    user="root",    #账户
    password="5863AXzy@"    #密码
)


# print(conn.get_server_info())#打印出数据库的基本信息

#执行非查询性质SQL
# cursor=conn.cursor()    #获取游标对象
# #选择数据库
# conn.select_db("students")
# #执行sql          #传入sql语句
# cursor.execute("create table students_pymysql(id int);")#创建一个在students库下的students_pymysql表    #分号可不写


#执行查询性质的SQL
cursor=conn.cursor()    #获取游标对象
#选择数据库
conn.select_db("students")
#执行sql          #传入sql语句
cursor.execute("select * from student")
#拿到上述语句的结果
results=cursor.fetchall()   #生成的是元组
for r in results:
    print(r)
#关闭链接
conn.close()

commit-提交

sql 复制代码
from pymysql import Connection


#构建到MySQL数据库的链接
conn=Connection(
    host="localhost",   #主机名
    port=3306,  #端口
    user="root",    #账户
    password="5863AXzy@"    #密码
)

#执行查询性质的SQL
cursor=conn.cursor()    #获取游标对象
#选择数据库
conn.select_db("students")
#执行sql          #传入sql语句
cursor.execute("insert into student values(1,'张学友',23)")
#通过commit确认
conn.commit()
#关闭链接
conn.close()

自动commit

sql 复制代码
from pymysql import Connection


#构建到MySQL数据库的链接
conn=Connection(
    host="localhost",   #主机名
    port=3306,  #端口
    user="root",    #账户
    password="5863AXzy@",    #密码
    autocommit=True #自动提交
)

#执行查询性质的SQL
cursor=conn.cursor()    #获取游标对象
#选择数据库
conn.select_db("students")
#执行sql          #传入sql语句
cursor.execute("insert into student values(1,'林俊杰',23)")

#关闭链接
conn.close()

综合案例

DDL定义

sql 复制代码
"""
SQL 综合案例,读取文件,写入MySQL
"""
from file_define import  TextFileReader, JsonFileReader
from data_define import Record
from pymysql import Connection

text_file_reader = TextFileReader("D:/2011年1月销售数据.txt")
json_file_reader = JsonFileReader("D:/2011年2月销售数据JSON.txt")

jan_data: list[Record] = text_file_reader.read_data()
feb_data: list[Record] = json_file_reader.read_data()
# 将2个月份的数据合并为1个list来存储
all_data: list[Record] = jan_data + feb_data

#构建MySQL链接对象
conn=Connection(
    host="localhost",
    port=3306,
    user="root",
    password="5863AXzy@",
    autocommit=True
)
#获得游标对象
cursor=conn.cursor()
#选择数据库
conn.select_db("py_sql")
#组织SQL语句
for record in all_data:
    sql = "INSERT INTO orders(order_date, order_id, money, province) VALUES (%s, %s, %s, %s)"
    cursor.execute(sql, (record.date, record.order_id, record.money, record.province))


conn.close()

若有侵权,请联系作者

相关推荐
星辰离彬28 分钟前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
张璐月3 小时前
mysql join语句、全表扫描 执行优化与访问冷数据对内存命中率的影响
数据库·mysql
全干engineer5 小时前
ClickHouse 入门详解:它到底是什么、优缺点、和主流数据库对比、适合哪些场景?
数据库·clickhouse
Hellyc7 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
lifallen7 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
{⌐■_■}11 小时前
【Kafka】登录日志处理的三次阶梯式优化实践:从同步写入到Kafka多分区批处理
数据库·分布式·mysql·kafka·go
isNotNullX11 小时前
数据中台架构解析:湖仓一体的实战设计
java·大数据·数据库·架构·spark
睿思达DBA_WGX14 小时前
由 DB_FILES 参数导致的 dg 服务器无法同步问题
运维·数据库·oracle
袋鼠云数栈15 小时前
使用自然语言体验对话式MySQL数据库运维
大数据·运维·数据库·后端·mysql·ai·数据治理·数栈·data+ai