#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, create_engine, Integer, MetaData, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class User(Base):
# 表的名字:
__tablename__ = 'user'
# 表的结构:
id = Column(Integer(), primary_key=True)
name = Column(String(20))
age = Column(Integer())
# 初始化数据库连接:
engine = create_engine('mysql+pymysql://root:password@localhost:3306/common')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 创建表
Base.metadata.create_all(engine)
def add_user(name, age):
# 创建session对象:
session = DBSession()
# 创建新User对象:
new_user = User(name=name, age=age)
# 添加到session:
session.add(new_user)
# 提交即保存到数据库:
session.commit()
# 关闭session:
session.close()
def get_user(name):
# 创建Session:
session = DBSession()
# 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:
user = session.query(User).filter(User.name == name).one()
# 打印类型和对象的name属性:
print('age:', user.age)
print('name:', user.name)
# 关闭Session:
session.close()
################################################操作已有数据库###########################################################################
metadata = MetaData(bind=engine)
class Province(Base):
'''映射已有的数据库,传入三个参数:数据库名称、metadata(绑定接口)、autoload=True'''
__table__ = Table('province', metadata, autoload=True)
def get_pname_from_exist_database(code):
session = DBSession()
target = session.query(Province).filter(Province.code == code).one()
print('code:', target.code)
print('name:', target.pname)
# 关闭Session:
session.close()
if __name__ == '__main__':
add_user('user01',22)
get_user('user01')
#查询已有数据库
get_pname_from_exist_database('ZJ')
数据去重:
CREATE TABLE table_temp AS
SELECT * FROM table GROUP BY title, SID;
DROP TABLE table;
RENAME TABLE table_temp TO table;