• Python使用ORM:sqlalchemy


    # -*- coding: utf-8 -*-
    # Author: areful
    
    # needs module 'mysql-connector-python', 'sqlalchemy', running command below to install it:
    # pip install mysql-connector-python
    # pip install sqlalchemy
    
    # 导入:
    from sqlalchemy import Column, String, create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    # 创建对象的基类:
    Base = declarative_base()
    
    
    # 定义User对象:
    class User(Base):
        # 表的名字:
        __tablename__ = 'user'
    
        # 表的结构:
        id = Column(String(20), primary_key=True)
        name = Column(String(20))
    
    
    # 初始化数据库连接:
    engine = create_engine('mysql+mysqlconnector://root:123456@192.168.147.130:3306/test')
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    
    # 创建session对象:
    session = DBSession()
    # 创建新User对象:
    new_user = User(id='5', name='Bob')
    # 添加到session:
    session.add(new_user)
    # 提交即保存到数据库:
    session.commit()
    # 关闭session:
    session.close()
    
    # 创建Session:
    session = DBSession()
    # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:
    user = session.query(User).filter(User.id == '5').one()
    # 打印类型和对象的name属性:
    print('type:', type(user))
    print('name:', user.name)
    # 关闭Session:
    session.close()
    

      

  • 相关阅读:
    从yum源下载软件包
    本地yum源建立
    Redis慢查询,redis-cli,redis-benchmark,info
    Centos6.6安装mysql记录
    Nginx常用命令(加入系统服务)
    Nginx+keepalived双机热备(主从模式)
    Nginx反向代理+负载均衡简单实现
    Centos7安装Python3.5
    CentOS 6.4下OpenSSH升级到6.7操作
    Redis详解
  • 原文地址:https://www.cnblogs.com/areful/p/10369586.html
Copyright © 2020-2023  润新知