![]()
#encoding: utf-8
from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text,\
ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from random import randint
HOSTNAME = '127.0.0.1'
PORT = 3306
DATABASE = 'first_sqlalchemy'
USERNAME = 'root'
PASSWORD = '123456'
#dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" \
"{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)
engine = create_engine(DB_URI)
Base = declarative_base(engine)
# Session = sessionmaker(engine)
# session = Session()
session = sessionmaker(engine)() #Session(**local_kw)
#父表/从表
#user/article
class User(Base):
__tablename__ = 'user'
id = Column(Integer,primary_key=True,autoincrement=True)
username = Column(String(32),nullable=False)
class Article(Base):
__tablename__ = 'article'
id = Column(Integer,primary_key=True,autoincrement=True)
title = Column(String(50),nullable=False)
content = Column(Text,nullable=False)
#引用主表的外键一定要跟主表的数据类型相同
#restrict 本意是拒绝的意思,no action 也是,从表(子表)关联了主表,
#关联字段 ondelect = 'RESTRICT' 或 ondelect = 'NO ACTION',主表删除会报错,
#不允许删除
#如果 设置 ondelect = "CASCADE",主表删除,子表也会随之删除
#如果 设置 ondelect = "SET NULL",主表删除,子表的关联字段会表设置null
#也就是uid = null ,还有一种情况就是 nullable 不能设置成False
uid = Column(Integer,ForeignKey('user.id',ondelete='RESTRICT'))
Base.metadata.drop_all()
Base.metadata.create_all()
# 查看 表创建的sql 语句
# show create table article\G;
'''
Create Table: CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`content` text NOT NULL,
`uid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
CONSTRAINT `article_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
'''
#添加数据
user = User(username = 'xiaowu')
session.add(user)
session.commit()
article = Article(title = '圣墟',content = '吹牛逼死坑的小说,天天吹水逼',uid = 1)
session.add(article)
session.commit()
#删除一条记录的sql delete from user where id = 1;