Python 第四十三章 MYSQL 补充

49 篇文章 0 订阅
35 篇文章 0 订阅

多表查询

1.笛卡尔积:将两表所有的数据一一对应,生成一张大表

select * from dep,emp;  #两个表拼一起
select * from dep,emp where dep.id = emp.dep_id; #找到两表之间对应的关系记录
select * from dep,emp where dep.id = emp.dep_id and dep.name='技术'; #筛选部门名称为技术的大表中的记录
select emp.name from dep,emp where dep.id = emp.dep_id and dep.name='技术'; #拿到筛选后的记录的员工姓名字段数据

  1. 连表查询

  2. inner join 内连接

第一步:连表
select * from dep inner join emp on dep.id=emp.dep_id;
第二步: 过滤
select * from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';
第三步:找对应字段数据
select emp.name from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';

left join 左连接(left join左边的表为主表,主表记录必须全部显示,辅表没办法对应上的,就通过null来补全)

select * from dep left join emp on dep.id=emp.dep_id;

right join 右连接

select * from dep right join emp on dep.id=emp.dep_id;

union 全连接

mysql> select * from dep left join emp on dep.id=emp.dep_id
-> union
-> select * from dep right join emp on dep.id=emp.dep_id;

子查询:(一个查询结果集作为另一个查询的条件)

select name from emp where dep_id = (select id from dep where name = '技术');

Navicat工具使用

看博客

pymysql python连接mysql的客户端

import pymysql
conn = pymysql.connect(
	host='127.0.0.1', #主机
	port=3306, #端口号
	user='root',#用户名
	password='666', #密码
	database='day43', #需要连接的库
	charset='utf8'
)
cursor = conn.cursor()

sql = "select * from dep;"
ret = cursor.execute(sql) #ret 受影响的行数
print(cursor.fetchall())  #取出所有的
print(cursor.fetchmany(3))  #取出多条
print(cursor.fetchone())  #取出单条

cursor.scroll(3,'absolute')  #绝对移动,按照数据最开始位置往下移动3条
cursor.scroll(3,'relative')  #相对移动,按照当前光标位置往下移动3条

conn.commit()  #增删改操作时,需要进行提交


sql注入:解决方案
	cursor.execute(sql,[参数1,参数2...])
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值