Python 第四十三章 MYSQL 补充

多表查询

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...])

原文地址:https://www.cnblogs.com/zhangshan33/p/11497832.html