回顧
# 完整的語法結構
select distinct * from 表名
where 分組以前的過濾條件
group by 分組依據
having 分組
order by 字段1 asc,字段2 desc
limit 5,5 從第五條開始日後展現五條
#where 後面的過濾條件能夠跟判斷符號(>,<,in ,not in,=),(注意判斷是否爲null的時候不能用=,只能用is)能夠跟模糊判斷(like '%',_標識任意一個字符)
# char_length(字段名):查看字段中數據的長度
# concat 鏈接字符
select concat(name,':',age) from emp;
# 若是鏈接符號都同樣的話能夠用concat_ws
select concat_ws(':',name,age,post) from emp;
# group_concat 分組以後進行鏈接
# 多表查詢
inner join # 內鏈接
left join # 左鏈接
right join # 右鏈接
union # 全鏈接
補充(瞭解)
exist
EXISTS關字鍵字表示存在。在使用EXISTS關鍵字時,內層查詢語句不返回查詢的記錄,
而是返回一個真假值,True或False。
當返回True時,外層查詢語句將進行查詢
當返回值爲False時,外層查詢語句不進行查詢。
select * from emp where exists (select * from dep where 1=2); # Empty set (0.01 sec)
select * from emp where exists (select * from dep where id >1);
Navicat使用
# 須要掌握的
#1.測試+連接數據庫
#2.新建庫
#3.新建表,新增字段+類型+約束
#4.設計表:外鍵
#5.新建表查詢
#6.創建表模型
#注意:
批量加註釋:ctrl+?鍵
批量去註釋:Ctrl+shift+?鍵
pymysql模塊
# 1.安裝:pip3 install pymysql
# 2.代碼連接
import pymysql
#連接
conn = pymysql.connect(
host='localhost',
user='root',
password='123',
database='lucas',
charset='utf8',
autocommit=True)
# 遊標
cursor=conn.cursor() #執行完畢返回的結果默認以元組顯示
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) 以字典的方式 顯示數據
# 3.pymysql操做數據庫
# 執行sql語句
user=input('>>>:').strip()
pwd=input('>>>:').strip()
sql='select * from userinfo where name="%s" and password="%s"'%(user,pwd) # 注意%s須要加引號
rows = cursor.execute(sql) # 執行sql語句,返回sql查詢成功的記錄數目
# 獲取真實數據
res = cursor.fetchone() # 獲取一條
res = cursor.fetchall() # 獲取全部
res = cursor.fetchmany() # 獲取多條
cursor.scroll(1,'relative') #相對移動,遊標從當前位置日後移動一個
cursor.scroll(1,'absolute') #絕對移動,遊標從頭開始日後移動1個
cursor.close()
conn.close()
sql注入
# 不要手動去拼接查詢的sql語句
username = input(">>>:").strip()
password = input(">>>:").strip()
sql = "select * from user where username='%s' and password='%s'"%(username,password)
# 用戶名正確
username >>>: jason' -- jjsakfjjdkjjkjs
# 用戶名密碼都不對的狀況
username >>>: xxx' or 1=1 --asdjkdklqwjdjkjasdljad
password >>>: ''
#以上兩種狀況都能進入數據庫,因此應該由數據庫去判斷
username = input(">>>:").strip()
password = input(">>>:").strip()
sql = "select * from user where username=%s and password=%s"
rows = cursor.execute(sql,(username,password))
增刪改
#增
sql = "insert into user(username,password) values(%s,%s)"
rows = cursor.excute(sql,('lucas','123'))
#修改
sql = "update user set username='ymg' where id=1"
rows = cursor.excute(sql)
#一次插入多行記錄
rows=cursor.excutemany(sql,[(),(),()])
#增和改單單執行excute並不會真正影響到數據,須要再執行conn.commit()才能夠完成真正的增改,也能夠直接在建連接的時候加上:autocommit=True