连表操作:
##将两张表拼合在一起
##结果为笛卡尔积
select * from dep,emp;
#
select * from emp,dep where emp.dep_id = dep.id;
mysql也知道 你在后面查询数据时 肯定会用到拼表操作
所以特地的开设了对应方法
inner join 内连接 只拼接两张表中公有的数据(不能拼接无关系的)
left join 左连接 把左边的表作为主表 (展示左表所有的数据没有的数据用null代替)
right join 右连接 把右边的表作为主表 (展示右表所有的数据没有的数据用null代替)
union 全连接 所有数据全展示
###全连接比较麻烦###
select * from emp right join dep on emp.dep_id=dep.id
union
select * from emp left join dep on emp.dep_id=dep.id;
#例
select * from emp inner join dep on emp.dep_id=dep.id;
子查询:
子查询就是我们平时结局问题的思路,就是分布查询
将 第一个查询语句的结果当成查询的条件去用
#查询部门是技术或者人力资源的员工信息
1.先获取部门id
select id from dep where name="技术" or "人力资源";
2.在去员工表里面筛选出对应的员工数据
select * from emp where dep in (部门id);
#合并
select * from emp where dep in (select id from dep where name="技术" or "人力资源";);
##表的查询结果可以作为其他表的查询条件
##也可以通过给表起别名的方法把他作为一张虚拟表和其他表查询
navicat可视化界面做数据库
安装:一个破解版 (安装步骤来即可) 官网安装
##utf8mb4可以存储表情
##navicat并不是万能的有时候你无法通过navicat实现所以当时你只能手码##
sql语句中注释:# 或者–
快捷键:ctrl+?
pymsql模块
pymsql开发者文档
##支持python代码操作数据库##
连接数据库
import pymysql
#连接数据库
connect=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password="********",
charset="utf8" #注意这里是utf8不是utf-8
)
生成游标对象
##就等于在cmd窗口登录后后产生一个光标
cursor=connect.cursor() #产生游标对象
导入表
import pymysql
#连接数据库
connect=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
#这里添加数据库名
database="数据库名",
password="********",
charset="utf8" #注意这里是utf8不是utf-8
)
cursor=connect.cursor() #产生游标对象
输入sql语句
cursor=connect.cursor()
#输入sql语句
sql='select * from 表名;'
#execute返回sql语句拿出了几条数据
res=cursor.execute(sql)
基本使用方式
#以当前光标开始获取一条对象并移动一位
res= cursor.fetchone()
#将查询结果以字典形式返回
cursor=connect.cursor(cursor=pymsql.cursors.DictCursor)
res= cursor.fetchone()
#从当前光标开始拿出所有数据
res= cursor.fetchall()
#注意fetchone()读取数据类似与光标的移动
res= cursor.fetchone()
res= cursor.fetchone()
#代码结果相当于第二条数据
#相对光标移动 这个相当于只移动光标不读取
cursor.scroll(光标移动位数,“relative”)
#绝对移动 这个相当于从头开始移动光标
cursor.scroll(光标移动位数,“absolute”)
sql注入问题
利用语法的特性 书写一些特点的语法实现固定的语法
mysql利用的是mysql的注释语法
怕你构造出特定的语法入侵数据库 不安全
##1利用正则筛选出特定符号1##
##2pymsql特定封装函数2##
userword=input("密码:")
password=input("账号:")
sql="select * from user where name=%s and password=%s"
#不要拼接用%s占位 之后将数据直接交给execute方法即可
row=cursor.execute(sql,(userword,password))
#实现数据增加
sql="insert into user(name,password) values(%s,%s);"
cursor.execute(sql,("mzy",123))
#提交数据(查看不需要commit这一操作)
conn.commit()
#或者不使用也可以需要修改配置
connect=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
#这里添加数据库名
database="数据库名",
password="********",
charset="utf8", #注意这里是utf8不是utf-8
#这一步是为了不加入commit命令
autocommit=True
)
#其余涉及到数据修改(增删改查)操作类似(sql语句学好,木得问题)
#增加多个
sql="insert into user(name,password) values(%s,%s);"
#增加多个
cursor.executemany(sql,[("mzy",123),("lwj",123),("lfl",123)])
唔,数据库学完了感觉学完之后有点懵,可能这就是咸鱼了么QAQ