1. 程式人生 > >mysql相關復習

mysql相關復習

常用 AS sha .com index final form sel insert

1、常用sql操作

創建一個test庫:create database test;
授權一個用戶:grant all privileges on *.* to ‘user‘@‘%‘ identified by ‘password‘;
創建表:create table student(id int not null);
查詢:select * from tabel_name where 條件1 and 條件2
增加:insert into table_name (id, name, age, sex, grander) values (1, ‘ling‘, 25, ‘M‘, 99), (2, ‘ajing‘, 45, ‘F‘, 88);


修改:update table_name set id=10 where 條件判斷
刪除條件:delete from table_name where 條件判斷
刪除表:drop table table_name
聯合查詢:select a.id, b.name from A a join B b on a.id=b.tid
創建索引:create index idx_庫名_表名_列名1_列名2 (列名1, 列名2)
查看sql是否走索引:explain select * from student where name=‘ling‘
鏈接數據庫:Python2 使用的是MySQLdb,python3 使用的pymysql 可以使用pip安裝

2、python連接數據庫操作

①、 創建鏈接和遊標
註意:在mysql連接中,盡量使用一個連接,確保mysql的並發數
conn = pymysql.connect(host=‘‘, port=, user=‘‘, passwd=‘‘, db=‘‘)
cus = conn.curse()

②、執行sql
sql = "select * from Student;"
cus.execute(sql)
cus.fetchone() 獲取單個 返回值 tuple
cus.fetchall() 獲取多個 返回值 list(單個元素是tuple)
cus.fetchmany(size=n) 獲取多個

③、關閉遊標和連接


cus.close()
conn.close()
註意結合try exception finally的使用

3、SQLAlchemy操作

①、創建引擎
engine = create_engine(‘mysql+pymysql://username:password@hostname:port/db‘)

②、創建session
DBsession = sessionmaker(bind=engine)
session = DBsession()

③、創建表
a. 獲得engine
b. metadata = MetaData(engine)
c. student = Table(‘表名‘, metadata, Colume(‘id‘, Integer, primary_key=True), Colume(‘name‘, String(50))
d. metadata.create_all()

④、增加
a. 先要有一個模型
Base = declarative_base(0
class Student(Base):
__tablename__ = ‘student‘
id = Column(Integer, primary_key=True)
name = Column(String(100), primary_key=True)
b. 導入模型類,實例化該類,
sutdent1 = Student(1, ‘ling‘)
c. session.add(單實例) session.add_all([實例1, 實例2])

⑤、查詢
filter和filter_by的區別
filter:可以使用> < 等,但是列必須是: 表.列, filter的等於號是==
session.query(Student).filter(Student.id>100)
filter 不支持組合查詢
session.query(Student).filter(Studnet.id>100).filter(name==‘ling‘)
filter_by: 可以直接寫列,不支持< > filter_by 等於是==
session.query(Student).filter_by(id==10)
filter_by 可以支持組合查詢
session.query(Student).filter_by(name==‘ling‘ and id==‘342‘)
select * from student where name like ‘%ling%‘;
模糊查詢含有ling的關鍵字
模糊查詢
session.query(Student).filter(Student.name like(‘%ling%‘))
獲取數據的時候有兩個方法:
one() tuple
all() list(單個元素是tuple)
如果在查詢中不寫one(), 或者all() 出來的就是sql語句

⑥、更新
1)、先查出來
2)、跟新一下類所對應的屬性值就ok
3)、session.commit()
student1 = session.query(Student).filter(Student.id==1001)
student1.name = "test"
session.commit()

⑦、刪除
1)、先查出來
2)、直接調用delete()方法就可以
3)、提交一下

⑧、統計、 分組、排序
統計:count()
只需要在查出來以後, 把one或者all替換成count()
統計有多少個
分組:group_by
查出來以後,把one或者all替換成group_by(屬性)

4、示例:

from sqlalchemy import create_engine, Integer, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


Base = declarative_base()
class Student(Base):
__tablename__ = ‘student‘
id = Column(Integer, primary_key=True)
name = Column(String(100))
age = Column(Integer)
address = Column(String(100))

def update(session):
student1 = session.query(Student).filter(Student.id == 1001).one()
student1.name=‘test123‘
session.commit()
student2 = session.query(Student).filter(Student.id == 1001).one()
print(student2.name)

def delete(session):
session.query(Student).filter(Student.id == 1001).delete()
session.commit()

def insert(session):
student1 = Student(id=1004, name=‘ling‘, age=28, address=‘shanxi‘)
session.add(student1)
session.commit()

def count(session):
numnber = session.query(Student).filter().count()
print("total student is {0}".format(numnber))

def groupBy(session):
groupByAge = session.query(Student).group_by(Student.age).all()
print(groupByAge)
for i in groupByAge:
print(i.id, i.name, i.age, i.address)

def orderBy(session):
orderByAge = session.query(Student).order_by(Student.age.desc()).all()
for x in orderByAge:
print(x.id, x.name, x.age, x.address)

def main():
engine = create_engine(‘mysql+pymysql://xiang:[email protected]/sqlalchemy‘)
DBsession = sessionmaker(bind=engine)
session = DBsession()
# insert(session)
# update(session)
# delete(session)
# count(session)
# groupBy(session)
orderBy(session)


if __name__ == ‘__main__‘:
main()

mysql相關復習