连接postgresql
# psycopg2
engine=create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')#
Engine.execute()orEngine.connect()is called, the Engine establishes a real DBAPI connection to the database, which is then used to emit the SQL.2 from sqlalchemy.schema import MetaData, Table, Column, ForeignKey, Sequence
3 from sqlalchemy.types import *
4
5 engine = create_engine('postgres://test:test@localhost/test', echo=True)
6
7 metadata = MetaData()
8 metadata.bind = engine
9
10 book_table = Table('book', metadata,
11 Column('id', Integer, Sequence('seq_pk'), primary_key=True),
12 Column('title', Unicode(255), nullable=False),
13 )
14
15 author_table = Table('author', metadata,
16 Column('id', Integer, Sequence('seq_pk'), primary_key=True),
17 Column('name', Unicode(255), nullable=False),
18 )
19
20 bookauthor_table = Table('bookauthor', metadata,
21 Column('book_id', Integer, ForeignKey('book.id'), nullable=False),
22 Column('author_id', Integer, ForeignKey('author.id'), nullable=False),
23)
24
25metadata.create_all(checkfirst=True)
首先我们还是create_engine,然后新建一个MetaData对象,把engine绑上去,接下来,开始在metadata中定义表结构(metadata由Table构造函数传入),我们这里定义了3张表,分别是book、author和bookauthor关系表(“多对多”),其中新建一个Sequence对象,专门处理主键生成。最后我们通过执行metadata.create_all()创建数据库表,参数checkfirst=True表示如果数据库相关对象已经存在,则不重复执行创建。
对于已经存在于数据库中的表,我们可以通过传入autoload=True参数到Table构造函数的方式来加载现有的表结构到metadata中,而不必挨个儿再写一遍Column清单。
看到这儿,你也许觉得挺麻烦,不是么?Django和RoR都是可以直接定义数据model类,顺带就把schema也定义了,而不是像这样单独去写表结构的schema,显得很"底层"。确实,这样用SQLAlchemy并不是最优化的,SQLAlchemy本身并不会自动的帮你做很多事,但它基础打得很牢。如果你感兴趣,也可以先去看一下SQLAlchemy的扩展模块Elixir,通过Elixir,你可以像Ruby on Rails那样定义出实体和关系("Active Record")。
文/人世间(简书作者)原文链接: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,selectengine = create_engine('postgresql+psycopg2://postgres:root@localhost:5432/blogdb')metadata = MetaData()metadata.bind = engineauth_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()
连接postgresql的更多相关文章
- ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库
前段时间在园子里看到了小蝶惊鸿 发布的有关绿色版的Linux.NET——“Jws.Mono”.由于我对.Net程序跑在Linux上非常感兴趣,自己也看了一些有关mono的资料,但是一直没有时间抽出时间 ...
- 视频教程--ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库
说好的给园子里的朋友们录制与<ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库> 这篇博客相对应的视频,由于一个月一来没有时 ...
- kali linux 系列教程之metasploit 连接postgresql可能遇见的问题
kali linux 系列教程之metasploit 连接postgresql可能遇见的问题 文/玄魂 目录 kali linux 下metasploit 连接postgresql可能遇见的问题. ...
- Entity Freamwork 6连接PostgreSql数据库
原文 Entity Freamwork 6连接PostgreSql数据库 开发环境 VS 2015 Update 1 Postgre Sql 9.4 使用过程 1.使用Nuget在项目中添加对E ...
- php连接postgresql
在ubuntu下用php连接postgresql需要下个模块php5-pgsql 连接数据库并显示一张表的内容: <?php #连接数据库 $conn = pg_connect("ho ...
- python连接postgresql数据库
python可以通过第三方模块连接postgresql. 比较有名的有psycopg2 和python3-postgresql (一)psycopg2 ubuntu下安装 sudo apt-get ...
- Abp.NHibernate连接PostgreSQl数据库
Abp.NHibernate动态库连接PostgreSQl数据库 初次接触Abp框架,其框架中封装的操作各类数据的方法还是很好用的,本人还在进一步的学习当中,并将利用abp.NHibernate类库操 ...
- QT连接postgreSQL
这是我之前项目遇到的问题,连接postgreSQL数据库,一直找不到引擎,最后终于找到 原因了,需要程序加载 1.安装postgresql客户端,2.需要配置postgresql客户端的bin和lib ...
- win7 安装用mingw编译的Qt源码并连接postgresql
下载Qt 1.下载qt-creator-windows-opensource-2.8.0,下载路径:http://download.qt.io/official_releases/qtcreator/ ...
- python2/3 利用psycopg2 连接postgreSQL数据库。
psycopg2 是一个通过python连接postgreSQL的库, 不要被它的名称蒙蔽了,你可能发现它的版本是psyconpg2.7.*, 以为它只能在python2上使用,实际上,这只是一个巧合 ...
随机推荐
- 开发高性能的MongoDB应用—浅谈MongoDB性能优化
关联文章索引: 大数据时代的数据存储,非关系型数据库MongoDB 性能与用户量 “如何能让软件拥有更高的性能?”,我想这是一个大部分开发者都思考过的问题.性能往往决定了一个软件的质量,如果你开发的是 ...
- "/usr/local/openresty/nginx/html/index.html" is forbidden (13: Permission denied), client: 10.0.4.118, server: localhost, request: "GET / HTTP/1.1"
openrestry 安装之后 报"/usr/local/openresty/nginx/html/index.html" is forbidden (13: Permission ...
- hdu6007 Mr. Panda and Crystal 最短路+完全背包
/** 题目:hdu6007 Mr. Panda and Crystal 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6007 题意:魔法师有m能量,有n ...
- jquery Fancybox使用教程
Fancybox是一款基于jquery的对图片展示播放的插件,当然,它html文本.flash动画.iframe以及ajax也予以支持.还可以通过css自定义外观,阴影效果超级赞! 演示效果:http ...
- 反向传播BackPropagation
http://www.cnblogs.com/charlotte77/p/5629865.html http://www.cnblogs.com/daniel-D/archive/2013/06/03 ...
- win7(64位)+vs2008配置Directshow
参考链接:http://zhuyanfeng.com/archives/1663 PC环境:win7 64bit + vs2008 1.下载64位的win7 SDK2.安装过程中遇到错误(必须要卸载v ...
- Django之前端模板继承
在使用Django进行web开发时,往往会构造一个基础框架模板即base.html,而后在其子模板中对它所包含站点公用部分和定义块进行重载. 首先创建一个base.html,源码为: <!DOC ...
- 【BZOJ1509】[NOI2003]逃学的小孩 直径
[BZOJ1509][NOI2003]逃学的小孩 Description Input 第一行是两个整数N(3 N 200000)和M,分别表示居住点总数和街道总数.以下M行,每行给出一条街道的 ...
- ZooKeeper 基本介绍
Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问题,它能提供基于类似于文件系统的目录节点树方式的数据存储, Zookeeper 作用主要是用来维护和监控存储的数 ...
- JAVA 遍历文件夹下的所有文件(递归调用)
package file; import java.io.File; public class Test1 { public static void main(String[] args) { Str ...