标签:
# psycopg2
engine=create_engine(‘postgresql+psycopg2://scott:tiger@localhost/mydatabase‘)#
Engine.execute()
Engine.connect()
Engine
文/人世间(简书作者)
原文链接:http://www.jianshu.com/p/e6bba189fcbd
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
# -*- coding: utf-8 -*-
__author__ = ‘ghost‘
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey
# 连接数据库
engine = create_engine("mysql://root:@localhost:3306/webpy?charset=utf8",encoding="utf-8", echo=True)
# 获取元数据
metadata = MetaData()
# 定义表
user = Table(‘user‘, metadata,
Column(‘id‘, Integer, primary_key=True),
Column(‘name‘, String(20)),
Column(‘fullname‘, String(40)),
)
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(engine)
# 获取数据库连接
conn = engine.connect()
import sqlalchemy
import pnosql
class Confsql:
def __init__(self,dbstr="postgresql+psycopg2://postgres:root@localhost:5432/Usermodel"):
self.engine = sqlalchemy.create_engine(dbstr, echo=True)
self.metadata = sqlalchemy.MetaData()
self.metadata.bind = self.engine
def runquery(self, sqlstr):
s = sqlstr
result = self.engine.execute(sqlstr)
rows = result.fetchall()
result.close()
需要对返回的数据进行修改才行
def runsp(self,sqlstr):
s = sqlstr
result = self.engine.execute(sqlstr)
rows = result.fetchall()
result.close()
result = []
for row in rows:
x = {}
x["barcode"] = row[0]
x["spcode"] = row[1]
x["spname"] = row[2]
x["spformat"] = row[3]
x["height"] = row[4]
x["width"] = row[5]
x["thickness"] = row[6]
x["comp"] = ‘youke‘
x["parentcomp"] = ‘yz‘
x["_id"] = str(uuid.uuid1())
result.append(x)
return result
from sqlalchemy import create_engine,MetaData,Table,select
engine = create_engine(‘postgresql+psycopg2://postgres:root@localhost:5432/blogdb‘)
metadata = MetaData()
metadata.bind = engine
auth_permission = Table(‘auth_permission‘,metadata,autoload = True)
def query_code(codename):
info = {‘name‘:‘‘,‘codename‘:‘‘}
s = select([auth_permission.c.codename, auth_permission.c.name, ]).where(auth_permission.c.codename == codename)
codename_query = engine.execute(s)
for row in codename_query:
info[‘codename‘] = row[0]
info[‘name‘] = row[1]
codename_query.close()
return info
#修改权限
def updata(codename,name):
s = auth_permission.update().where(auth_permission.c.codename == codename).values(name=name,codename=codename)
c = engine.execute(s)
c.close()
# 添加权限
def add(codename,name,content_type_id):
s = auth_permission.insert().values(name=name,codename=codename,content_type_id=content_type_id)
c = engine.execute(s)
c.close()
# 删除权限
def delete(codename):
s = auth_permission.delete().where(auth_permission.c.codename == codename)
c = engine.execute(s)
c.close()
标签:
原文地址:http://www.cnblogs.com/wuqingzangyue/p/5770027.html