连接postgresql
生活随笔
收集整理的這篇文章主要介紹了
连接postgresql
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# psycopg2engine=create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')#
python 連接postgresql使用psycopg2作為默認的DBAPI
The first time a method like?Engine.execute()orEngine.connect()is called, the?Engine?establishes a real?DBAPI?connection to the database, which is then used to emit the SQL.
Thecreate_engine()function produces anEngineobject basedon a URL.
?1?from?sqlalchemy.engine?import?create_engine
?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()
sqlalchemy連接postgresql數據庫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
SqlAlchemy應用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()
來自為知筆記(Wiz)
python 連接postgresql使用psycopg2作為默認的DBAPI
The first time a method like?Engine.execute()orEngine.connect()is called, the?Engine?establishes a real?DBAPI?connection to the database, which is then used to emit the SQL.
Thecreate_engine()function produces anEngineobject basedon a URL.
?1?from?sqlalchemy.engine?import?create_engine
?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")。
sqlalchemy連接postgresql數據庫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
SqlAlchemy應用
來自為知筆記(Wiz)
轉載于:https://www.cnblogs.com/wuqingzangyue/p/5770027.html
總結
以上是生活随笔為你收集整理的连接postgresql的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql+Heartbeat+Drbd
- 下一篇: 模拟UIWebView