一.python连接mysql
from sqlalchemy import create_engine # 数据库数据 HOSTNAME = '127.0.0.1' # linux本地 PORT = '3306' DATABASE = 'mydb' USERNAME = 'admin' PASSWORD = 'Root110qwe' # 数据连接url db_url = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format( USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE ) # 连接到mysql需要用到pymysql engine = create_engine(db_url) # 链接数据库 # 建表需要 创建Modle的 Base类 from sqlalchemy.ext.declarative import declarative_base Base = declarative_base(engine) # 处理表的数据需要 创建会话 from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine) session = Session() # 测试连接 if __name__ == '__main__': connection = engine.connect() result = connection.execute('select 1') print(result.fetchone())
二.建表 需要 在连接时创建一个Base类
# 创建Modle的Base类u from sqlalchemy.ext.declarative import declarative_base Base = declarative_base(engine)
三.建表
通过python的 类 建表,这个类需要继承Base类 (依靠Base类将表和python的类连接起来)
* 需要继承Base类
from datetime import datetime from sqlalchemy import Column,Integer,String,DateTime from connect import Base # 把数据库的表映射成python的类(继承Base类) 用python中的类(继承Base类)来表示mysql的表 class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(20),nullable=False) password = Column(String(50)) creatime = Column(DateTime,default=datetime.now()) def __repr__(self): # 重写repr方法 return "<User(id=%s,username=%s,password=%s,createtime=%s)>" %( self.id, self.username, self.password, self.creatime ) if __name__ == '__main__': Base.metadata.create_all()
四.给建的表添加属性(增删改查)
* 需要创建会话
# 处理表的数据需要 在连接时 创建会话 from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine) session = Session()
————————————————————————————————————————————————————————————————————————————————————
增加属性:
from connect import session from user_module import User # 增加函数 def add_user(): person = User(username='budong',password='qwe123') session.add(person) # 添加单条数据 session.add_all( # 添加多条数据 [ User(username='tj',password='123qwe1'), User(username='tj1',password='123qwe2'), User(username='tj2',password='123qwe3') ] ) session.commit() # 处理数据必须提交事务 增加的属性结果
+----+----------+----------+---------------------+
| id | username | password | creatime |
+----+----------+----------+---------------------+
| 1 | budong | qwe123 | 2018-03-03 15:46:31 |
| 2 | tj | 123qwe1 | 2018-03-03 15:46:31 |
| 3 | tj1 | 123qwe2 | 2018-03-03 15:46:31 |
| 4 | tj2 | 123qwe3 | 2018-03-03 15:46:31 |
+----+----------+----------+---------------------+
def search_user(): rows = session.query(User).all() # all所有的数据 .first() 查询第一条数据 print(rows) # 这儿打印的是repr,所以需要在建表的时候重写repr方法
查询的数据结果
[<User(id=1,username=budong,password=qwe123,createtime=2018-03-03 16:14:35)>, <User(id=2,username=tj,password=123qwe1,createtime=2018-03-03 16:14:35)>, <User(id=3,username=tj1,password=123qwe2,createtime=2018-03-03 16:14:35)>, <User(id=4,username=tj2,password=123qwe3,createtime=2018-03-03 16:14:35)>]
def update_user(): session.query(User).filter(User.username=='tj1').update({User.password:'88888',User.username:'haha'}) session.commit()
修改的数据结果 --修改了tj1 = haha,password=88888
+----+----------+----------+---------------------+
| id | username | password | creatime |
+----+----------+----------+---------------------+
| 1 | budong | qwe123 | 2018-03-03 16:14:35 |
| 2 | tj | 123qwe1 | 2018-03-03 16:14:35 |
| 3 | haha | 88888 | 2018-03-03 16:14:35 |
| 4 | tj2 | 123qwe3 | 2018-03-03 16:14:35 |
+----+----------+----------+---------------------+
a
def delete_user(): row =session.query(User).filter(User.id==1)[0] # 相当于 .first() session.delete(row) session.commit()
删除数据的结果 --删除了第一条数据
+----+----------+----------+---------------------+
| id | username | password | creatime |
+----+----------+----------+---------------------+
| 2 | tj | 123qwe1 | 2018-03-03 16:14:35 |
| 3 | haha | 88888 | 2018-03-03 16:14:35 |
| 4 | tj2 | 123qwe3 | 2018-03-03 16:14:35 |
+----+----------+----------+---------------------+
if __name__ == '__main__': add_user() search_user() pdate_user() delete_user()