1. 标准创建表语句
CREATE TABLE `person`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(20) NOT NULL,
`age` INT NOT NULL DEFAULT 20,
`sex` SMALLINT DEFAULT 1,
`t_time` DATETIME NULL
) DEFAULT CHARSET='utf8';
2.标准插入数据语句
INSERT INTO `person` (`name`,`age`,`sex`,`t_time`) VALUES ("king",30,1,now());
插入多条
INSERT INTO `person` (`name`,`age`,`sex`,`t_time`) VALUES
("rose",40,1,now()),
("jack",50,1,now()),
("mary",60,1,now());
3.标准修改数据语句
UPDATE `person` SET `name`="SB" WHERE `name`="jack";
或者
UPDATE `person` SET `name`="SB" WHERE `id`=2;
...
4.标准删除数据语句
DELETE FROM `person` WHERE `id`=1;
...
5.标准查询数据语句
SELECT `person`.`name`, `person`.`age` FROM `person`
WHERE `age`<=50
GROUP BY ...
ORDER BY `age` DESC
LIMIT 0,3;
...
6.使用MySQLdb做增删改查↓
import MySQLdb
from datetime import datetime
class MySQLHelper(object):
def __init__(self):
self.get_connect()
def get_connect(self):
try:
self.conn = MySQLdb.connect(
user="root",
passwd="123456",
db="todo",
port=3306,
host="127.0.0.1",
charset="utf8",
)
except MySQLdb.Error as e:
print(e)
def get_closed(self):
self.conn.close()
def create_table(self):
my_sql = """
CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL ,
`age` INT NOT NULL DEFAULT 20,
`sex` SMALLINT NOT NULL DEFAULT 1,
`create_time` DATETIME ,
PRIMARY KEY (`id`)
) DEFAULT CHARSET utf8;
"""
try:
cur = self.conn.cursor()
cur.execute(my_sql)
except MySQLdb.Error as e:
print(e)
self.conn.rollback()
self.get_closed()
def insert(self):
my_sql = """
INSERT INTO `people` (`name`,`age`,`create_time`)
VALUES (%s, %s, %s)
"""
cur = self.conn.cursor()
try:
cur.execute(my_sql,("lily",18, datetime.now()),)
cur.execute(my_sql,("rose",27, datetime.now()),)
cur.execute(my_sql,("kara",30, datetime.now()),)
cur.execute(my_sql,("zero",23, datetime.now()),)
cur.execute(my_sql,("mary",54, datetime.now()),)
self.conn.commit()
except MySQLdb.Error as e:
print(e)
self.conn.rollback()
self.get_closed()
def update(self):
my_sql = """
UPDATE `people` SET `name`=%s WHERE `id`=1
"""
cur = self.conn.cursor()
try:
cur.execute(my_sql, ("Lily",))
self.conn.commit()
except MySQLdb.Error as e:
print(e)
self.conn.rollback()
self.get_closed()
def select(self):
my_sql = """
SELECT `people`.`sex`, SUM(`people`.`age`) FROM `people`
GROUP BY `people`.`sex`;
"""
cur = self.conn.cursor()
try:
cur.execute(my_sql)
print(cur.fetchall())
except MySQLdb.Error as e:
print(e)
self.get_closed()
def delete(self):
my_sql = """
DELETE FROM `people` WHERE `people`.`id`=1;
"""
cur = self.conn.cursor()
try:
cur.execute(my_sql)
self.conn.commit()
except MySQLdb.Error as e:
print(e)
self.conn.rollback()
self.get_closed()
def main():
m = MySQLHelper()
if __name__ == "__main__":
main()
7.使用sqlalchemy的经典样式创建表↓
from sqlalchemy import (Table, MetaData, create_engine,
Column, Integer, String, SmallInteger, DateTime)
from datetime import datetime
from sqlalchemy.orm import mapper, sessionmaker
engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
metadata = MetaData()
user = Table("user", metadata,
Column("id", Integer, nullable=False, primary_key=True, autoincrement=True),
Column("username", String(20), nullable=False),
Column("age", Integer, nullable=False),
Column("sex", SmallInteger, default=1),
Column("create_time", DateTime, default=datetime.now)
)
class User(object):
def __init__(self, username=None, age=None, sex=None):
if username:
self.username = username
if age:
self.age =age
if sex:
self.sex =sex
mapper(User, user)
if __name__ == "__main__":
Session = sessionmaker(bind=engine)
session = Session()
try:
user = User("rose", 20, 0)
session.add(user)
session.commit()
except Exception as e:
print(e)
session.rollback()
session.close()
8.使用sqlalchemy的orm样式创建表↓
from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (create_engine, Column, Integer, String, SmallInteger, DateTime)
from sqlalchemy.orm import Session
engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
Base = declarative_base()
class Human(Base):
__tablename__ = "human"
id = Column("id", Integer, autoincrement=True, primary_key=True)
name = Column("name", String(20), nullable=False, unique=True)
age = Column("age", Integer, nullable=False)
sex = Column("sex", SmallInteger, default=1)
create_time = Column("create_time", DateTime, default=datetime.now)
def __repr__(self):
return "name {}".format(self.name)
if __name__ == "__main__":
session = Session(bind=engine)
try:
res = []
for i in range(2,11):
h = Human(name="king00{}".format(str(i)), age=i, sex=1)
res.append(h)
session.add_all(res)
session.commit()
except Exception as e:
print(e)
session.rollback()
session.close()
9.使用sqlalchemy的经典样式反射存在的表↓
from datetime import datetime
from sqlalchemy import Table, create_engine, MetaData, select, func
engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
metadata = MetaData()
conn = engine.connect()
human = Table("human", metadata, autoload=True, autoload_with=engine)
metadata.reflect(bind=engine)
human = metadata.tables.get('human')
def insert():
ins = human.insert()
conn.execute(ins, [{"name":"ppp","age":20,"sex":1},{"name":"mmm","age":30,"sex":0}])
conn.close()
def insert2():
ins = human.insert().values(name="bbb", age=40, sex=0, create_time=datetime.now())
conn.execute(ins)
conn.close()
def update():
up = human.update().values(name="vvv").where(human.c.name=="bbb")
conn.execute(up)
conn.close()
def delete():
de = human.delete().where(human.c.name=="vvv")
conn.execute(de)
conn.close()
def _select():
s = select([human.c.name, human.c.age]).where(human.c.age>20).limit(2).offset(0)
res = conn.execute(s)
print(res.fetchall())
def _select2():
s = select([human.c.sex, func.count(human.c.id), func.sum(human.c.age)]).group_by(human.c.sex)
res = conn.execute(s)
print(res.fetchall())
def select3():
i = requirement.join(project, project.c.id==requirement.c.prj_id).join(product, product.c.id==project.c.prod_id)
s = select([project.c.prj_name.label("prj_name"), product.c.prod_name.label("prod_name"), requirement.c.req_name.label("req_name")]).select_from(i)
res = self.conn.execute(s).fetchall()
"""
SELECT project.prj_name AS prj_name, product.prod_name AS prod_name, requirement.req_name AS req_name
FROM requirement JOIN project ON project.id = requirement.prj_id JOIN product ON product.id = project.prod_id
"""
if __name__ == "__main__":
_select2()
10.使用sqlalchemy的ORM样式反射存在的表↓
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from datetime import datetime
engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
Base = automap_base()
Base.prepare(engine, reflect=True)
Human = Base.classes.human
session = Session(bind=engine)
def insert():
h = Human(name="vcr", age=67, sex=1, create_time=datetime.now())
session.add(h)
session.commit()
def update():
h_obj = session.query(Human).filter_by(name="vcr").first()
h_obj.name = "vccrr"
session.add(h_obj)
session.commit()
def delete():
h_obj = session.query(Human).filter_by(name="vccrr").first()
session.delete(h_obj)
session.commit()
def select():
res = session.query(Human).filter(Human.id > 7)
print([i for i in res])
if __name__ == "__main__":
select()