一、MySQL數(shù)據(jù)庫
1.安裝
sudo apt-get install mysql-server mysql-client
啟動
service mysql start
停止
service mysql stop
重啟
service mysql restart
查詢服務(wù)是否啟動
netstat -tap | grep mysql
連接服務(wù)器
mysql -hip -uname -ppasswd
創(chuàng)建數(shù)據(jù)庫
create database 數(shù)據(jù)庫名 charset = utf8;
刪除數(shù)據(jù)庫
drop database 數(shù)據(jù)庫名;
切換數(shù)據(jù)庫
use 數(shù)據(jù)庫名;
查看當(dāng)前選擇數(shù)據(jù)庫
select database();
創(chuàng)建表
命令中運(yùn)行
drop table if exisit 表名;
create table 表名(
id int primary key(主鍵) auto_increment(自動增長),
name varchar
)
修改表
alter table 表名 add|modify|drop 列名 類型;
如:
alter table students add birthday datetime;
刪除表
drop table 表名;
查看表結(jié)構(gòu)
desc 表名;
更改表名稱
rename table 原表名 to 新表名;
查看表的創(chuàng)建語句
show create table '表名';
修改
update 表名 set 列1=值1,... where 條件
刪除
delete from 表名 where 條件
2.查詢
select * from 表名 where 條件
select * from stu where name = ‘lisi’
where和having
where用在分組前
having用在分組后
在select后面列前使用distinct可以消除重復(fù)的行
select distinct gender from students
邏輯運(yùn)算符:and or not
select * from stu where id > 3 or name ='lisi'
模糊查詢:like,%表示任意多個字符,_表示一個字符
select * from stu where name lik '張%'
條件優(yōu)先級:小括號→not→比較運(yùn)算符→邏輯運(yùn)算符
3.聚合
聚合函數(shù):count,max,min,sum,avg
count:求總數(shù)
select count(*)from students
max:求最大
select max(id) from stu where gander = 0
min:求最小
select min(id) from stu
sum:求和
select sum(id) from stu where gender = 1
avg:求平均值
select avg(id) from stu
4.分組
順序:select
from
where
group by
having
limit
select max(id) from stu
where name = '張%'
group by gender
having age >=20
linmit 0,20
5.添加外聯(lián)
關(guān)聯(lián)的外鍵必須為主鍵,保持唯一性
create table scores(
id int primary key auto_increment
sname varchar
constraint stu_scores foreign key(sname) references students(id)
)
一對一和多對多的區(qū)別在于給外鍵設(shè)置UNIQUE,
多對多的情況下需要設(shè)置第三個關(guān)系表,先給關(guān)系表添加兩個外鍵,然后分別將兩個表的外鍵綁定到關(guān)系表的兩個外鍵上
drop table if exists students;
create table students(
sid int primary key auto_increment,
sname varchar(20)
);
drop table if exists teachers;
create table teachers(
tid int primary key auto_increment,
tname varchar(20)
);
drop table if exists reletion;
create table reletion(
stuid int not null,
tchid int
);
alter table reletion add constraint reletion_main primary key(stuid,tchid);
alter table reletion add constraint reletion_fk1 foreign key(stuid) references students(sid);
alter table reletion add constraint reletion_fk2 foreign key(tchid) references teachers(tid)
6.連接查詢
查詢男生的姓名、總分
select students.sname,sum(scores.score)
from scores
inner join students on scores.stuid=students.id
where students.gender=1
group by students.sname;
7.事務(wù)
數(shù)據(jù)庫的事務(wù)遵循四大特征(ACID):
原子性(Atomicity):事務(wù)中的全部操作在數(shù)據(jù)庫中是不可分割的,要么全部完成,要么均不執(zhí)行
一致性(Consistency):幾個并行執(zhí)行的事務(wù),其執(zhí)行結(jié)果必須與按某一順序串行執(zhí)行的結(jié)果相一致
隔離性(Isolation):事務(wù)的執(zhí)行不受其他事務(wù)的干擾,事務(wù)執(zhí)行的中間結(jié)果對其他事務(wù)必須是透明的
持久性(Durability):對于任意已提交事務(wù),系統(tǒng)必須保證該事務(wù)對數(shù)據(jù)庫的改變不被丟失,即使數(shù)據(jù)庫出現(xiàn)故障
· 要求:表的類型必須是innodb或bdb
類型,才可以對此表使用事務(wù)
8.與python交互
安裝pymysql
sudo apt install python3-pip3
pip3 install pymysql
用于建立與數(shù)據(jù)庫的連接
創(chuàng)建對象:調(diào)用connect()方法
conn = connect(參數(shù)列表)
對象的方法:
close()關(guān)閉連接
commit()事務(wù),所以需要提交才會生效
rollback()事務(wù),放棄之前的操作
cursor()返回Cursor對象,用于執(zhí)行sql語句并獲得結(jié)果
execute(operation [, parameters ])執(zhí)行語句,返回受影響的行數(shù)
fetchone()執(zhí)行查詢語句時,獲取查詢結(jié)果集的第一個行數(shù)據(jù),返回一個元組
fetchall()執(zhí)行查詢時,獲取結(jié)果集的所有行,一行構(gòu)成一個元組,再將這些元組裝入一個元組返回
scroll(value[,mode])將行指針移動到某個位置
增刪改
from pymysql import *
try:
conn = connect(host='localhost',port=3306,db='granblue_fantasy',user='root',passwd = '123',charset = 'utf8')
cur = conn.cursor()
#cur.execute("insert into student values(01,'張良')")
#cur.execute("update student set sname ='irlans' where id =01")
#cur.execute("delete from student where id = 01")
#params = [1,'lisi']
#cur.execute("insert into student value(%s,%s)",params)
#cur.execute("select sname from student where id = 1")
#ret = cur.fetchall()
#print(ret[0])
conn.commit()
cur.close()
except Exception as e:
print(e)
查詢一行數(shù)據(jù)
print(cur.fetchone())
查詢多行數(shù)據(jù)
print(cur.fetchall())
封裝:
from pymysql import *
from hashlib import *
class MySQLManager():
def __init__(self,host,port,db,user,passwd,charset='utf8'):
self.host = host
self.port = port
self.db = db
self.user = user
self.passwd = passwd
self.charset = charset
def connect(self):
self.conn = connect(host=self.host, port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
self.cur = self.conn.cursor()
def __edit(self,sql,params=None):
self.cur.execute(sql,params)
self.conn.commit()
def insert(self,sql,params=None):
self.__edit(sql,params)
def delete(self,sql,params=None):
self.__edit(sql,params)
def update(self,sql,params=None):
self.__edit(sql,params)
def serach_sigle(self,sql,params=None):
self.__edit(sql,params)
return self.cur.fetchone()
def serach_plu(self,sql,params=None):
self.__edit(sql,params)
return self.cur.fetchall()
def close(self):
self.cur.close()
self.conn.close()
def md5Encrypt(userPasswd):
mymd5 = md5()
mymd5.update(userPasswd.encode('utf-8'))
return mymd5.hexdigest()
def register():
userName = input('請輸入用戶名:')
userPasswd = input('請輸入密碼:')
userPasswd = md5Encrypt(userPasswd)
manager = MySQLManager('localhost',3306,'granblue_fantasy','root',123)
manager.connect()
sql = 'insert into userlist(username,passwd) value(%s,%s)'
params = [userName,userPasswd]
manager.insert(sql,params)
manager.close()
register()