create database test1;
grant all privileges on *.* to 'feng'@'%' identified by '1qaz@WSX';
create table Teacher( teaId int not null, teaname varchar(100), age int, sex enum('M', 'F'), phone int);
select * from tabel_name where 條件1 and 條件2
insert into table_name (id, name, age, sex, grander) values (1, 'feng', 30, '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)
explain select * from student where name='ling'
Python2 使用的是MySQLdb
python3 使用的pymysql pip安裝python
(1) 建立連接和遊標
注意:在mysql鏈接中,儘可能使用一個鏈接,確保mysql的併發數mysql
conn = pymysql.connect(host='', port=, user='', passwd='', db='') cus = conn.curse()
(2)執行sqlsql
sql = "select * from Student;" cus.execute(sql) cus.fetchone() 獲取單個 返回值 tuple cus.fetchall() 獲取多個 返回值 list(單個元素是tuple) cus.fetchmany(size=n) 獲取多個
(3) 關閉遊標和鏈接數據庫
cus.close() conn.close()
注意結合try exception finally的使用session
engine = create_engine('mysql+pymysql://username:password@hostname:port/db')
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()
(1) 先要有一個模型併發
Base = declarative_base(0 class Student(Base): __tablename__ = 'student' id = Column(Integer, primary_key=True) name = Column(String(100), primary_key=True)
(2)導入模型類,實例化該類,ide
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的關鍵字
模糊查詢fetch
session.query(Student).filter(Student.name like('%ling%'))
獲取數據的時候有兩個方法:
one() tuple
all() list(單個元素是tuple)
若是在查詢中不寫one(), 或者all() 出來的就是sql語句spa
(1) 先查出來
(2) 跟新一下類所對應的屬性值就ok
(3) session.commit()code
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(屬性)