sqlalchemy简单操作(创建表,反射表)

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做增删改查↓

# -*- coding: utf-8 -*-
# @Author: Lai

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()
    # m.create_table()
    # m.insert()
    # m.update()
    # m.select()
    # m.delete()


if __name__ == "__main__":
    main()

7.使用sqlalchemy的经典样式创建表↓

# -*- coding: utf-8 -*-
# @Author: Lai

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:123456@127.0.0.1/todo?charset=utf8")
metadata = MetaData()

# table
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)
    )

# model
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

# table与model映射
mapper(User, user)


if __name__ == "__main__":
    # metadata.create_all(bind=engine)  #建表
    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样式创建表↓

# -*- coding: utf-8 -*-
# @Author: Lai

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:123456@127.0.0.1/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__":
    # Base.metadata.create_all(bind=engine) # 建表
    session = Session(bind=engine)
    # h = Human(name="king001", age=30, sex=1)
    # session.add(h)
	
	# Human.__table__ ------------------------------>orm转经典类型
	
    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的经典样式反射存在的表↓

# -*- coding: utf-8 -*-
# @Author: Lai
from datetime import datetime
from sqlalchemy import Table, create_engine, MetaData, select, func

engine = create_engine("mysql+mysqldb://root:123456@127.0.0.1/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()

# 插入2
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())

# 查询2
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())

#product---->project---->requirement
# 查询3(连接查询)
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()
####################################################################
# 注意:多次连表查询,xxx_table.join(xx,xx==xx).join(xx,xx==xx)以此类推
####################################################################
"""
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样式反射存在的表↓

# -*- coding: utf-8 -*-
# @Author: Lai

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:123456@127.0.0.1/todo?charset=utf8")

Base = automap_base()
Base.prepare(engine, reflect=True)

# 反射得到orm
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.add_all([x,y])
    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()
posted @ 2023-09-12 22:27  lilied  阅读(1160)  评论(0编辑  收藏  举报