zoukankan      html  css  js  c++  java
  • 运用SQLAlchemy

    1. result = engine.execute(s)
    2. for row in result:
    3. Info["UserId"]=row[0]
    4. Info["UserTitle"] = row[1]
    5. Info["UserCode"] = row[2]
    6. Info["UserType"] = row[3]
    7. result.close()
    返回的result为一个元组,



    echo设置为True,目的是SqlAlchemy将会把执行sql命令的过程输出到标准输出。这主要是便于调试,但如果是用于生产环境中应该设置为False。
        
    客户端连接到数据库postgresql:
    客户端connect >sqlalchemy->psycopg2->DBAPI->postgresql

    engine = create_engine('postgresql+psycopg2://postgres:root@localhost:5432/ttt', echo=True)
    创建引擎:指定     要连接的数据库+数据库接口://帐号:密码@localhost:5432/数据库名称 

    metadata元数据,实例化metadata,绑定到engine上,相当于初始化了表结构

    user = Table('book',metadata,
    Column('id',Integer,primary_key=True),
    Column('name',String(20)),
    )
    用Table来创建表,表的名称,类型,字段定义
    user不是表名,是数据表book对应的类名

    metadata.create_all(checkfirst=True)
    创建数据表,checkfirst=True,数据库相关对象已经存在的化就不会在创建了

    定义列   查询行

    When we use literal(文字的) strings, the Core can’t adapt(适应) our SQL to work on different database backends. 
    也就是不推荐使用原生sql查询


    插入数据
    最方便的插入
    user.insert().execute([{'id':6,'name':'1183532@qq.com'},{'id':5,'name':'118352@qq.com'}])
    user.insert().execute(id=7, name='hello')

    删除指定数据
    coon.execute(user.delete().where(user.c.id == 7))
    清空表中的数据
    coon.execute(user.delete())

    更新数据
    s = user.update().where(user.c.id == 7).values(name='say hello')
    r = coon.execute(s)

    查询数据
    s = select([user.c.name,user.c.id])
    result = coon.execute(s)
    for row in result:
    print row
    s = select([user,])
    result = coon.execute(s)
    for row in result:
    print row




    #coding:utf-8
    from sqlalchemy import create_engine
    from sqlalchemy import MetaData,Column,Sequence,ForeignKey,Integer
    from sqlalchemy import Table,String
    from sqlalchemy.sql import select,text
    engine = create_engine('postgresql+psycopg2://postgres:root@localhost:5432/ttt', echo=True)
    metadata = MetaData()
    metadata.bind = engine
    #数据库表与对象之间的映射关系
    user = Table('book',metadata,
    Column('id',Integer,primary_key=True),
    Column('name',String(20)),
    )
    address = Table('address',metadata,
    Column('id',Integer,primary_key=True),
    Column('user_id',None,ForeignKey('user.id')),
    Column('email',String(60),nullable=False),
    )
    #创建数据表
    metadata.create_all(checkfirst=True)


























































































  • 相关阅读:
    Redis安装部署
    传输方式Topic和Queue的对比
    Hudson配置及使用
    linux 绿色版 bes 6.6服务安装
    LINUX磁盘管理
    并发用户数与 TPS 之间的关系
    性能测试场景
    计算并发用户数的五种方法
    让selenium自动化脚本运行的更快的技巧
    Jmeter学习
  • 原文地址:https://www.cnblogs.com/wuqingzangyue/p/5770026.html
Copyright © 2011-2022 走看看