連接postgresql

# psycopg2
engine=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")。

  1. 文/人世間(簡書作者)
  2. 原文鏈接:http://www.jianshu.com/p/e6bba189fcbd
  3. 著作權歸作者所有,轉載請聯系作者獲得授權,并標注“簡書作者”。
  4. # -*- coding: utf-8 -*-
  5. __author__ = 'ghost'
  6. from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey
  7. # 連接數據庫
  8. engine = create_engine("mysql://root:@localhost:3306/webpy?charset=utf8",encoding="utf-8", echo=True)
  9. # 獲取元數據
  10. metadata = MetaData()
  11. # 定義表
  12. user = Table('user', metadata,
  13. Column('id', Integer, primary_key=True),
  14. Column('name', String(20)),
  15. Column('fullname', String(40)),
  16. )
  17. address = Table('address', metadata,
  18. Column('id', Integer, primary_key=True),
  19. Column('user_id', None, ForeignKey('user.id')),
  20. Column('email', String(60), nullable=False)
  21. )
  22. # 創建數據表,如果數據表存在,則忽視
  23. metadata.create_all(engine)
  24. # 獲取數據庫連接
  25. 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應用
  1. from sqlalchemy import create_engine,MetaData,Table,select
  2. engine = create_engine('postgresql+psycopg2://postgres:root@localhost:5432/blogdb')
  3. metadata = MetaData()
  4. metadata.bind = engine
  5. auth_permission = Table('auth_permission',metadata,autoload = True)
查詢操作
  1. def query_code(codename):
  2. info = {'name':'','codename':''}
  3. s = select([auth_permission.c.codename, auth_permission.c.name, ]).where(auth_permission.c.codename == codename)
  4. codename_query = engine.execute(s)
  5. for row in codename_query:
  6. info['codename'] = row[0]
  7. info['name'] = row[1]
  8. codename_query.close()
  9. return info
修改操作
  1. #修改權限
  2. def updata(codename,name):
  3. s = auth_permission.update().where(auth_permission.c.codename == codename).values(name=name,codename=codename)
  4. c = engine.execute(s)
  5. c.close()
添加操作
  1. # 添加權限
  2. def add(codename,name,content_type_id):
  3. s = auth_permission.insert().values(name=name,codename=codename,content_type_id=content_type_id)
  4. c = engine.execute(s)
  5. c.close()
刪除操作
  1. # 刪除權限
  2. def delete(codename):
  3. s = auth_permission.delete().where(auth_permission.c.codename == codename)
  4. c = engine.execute(s)
  5. c.close()















來自為知筆記(Wiz)


轉載于:https://www.cnblogs.com/wuqingzangyue/p/5770027.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542729.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542729.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542729.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

n的階乘程序python_Python程序對N階乘的尾隨零進行計數

n的階乘程序pythonFormula used: 使用的公式: Trailing 0s in N! Count of 5s in prime factors of n! floor(n/5) floor(n/25) floor(n/125) ....Example: 例: Input: N 23Output: 4Factorial of 23 is 25852016738884976640000 which has four …

c mysql使用場景_Mysql 場景

1個SQL題,1個場景題,會有點難度!SQL題該SQL題大量涉及到row_number,case when,group by等高級用法,有一定的實用價值,總結出來,供日后參考Question.1:分組匯總給定篩選條…

以己為壑

2019獨角獸企業重金招聘Python工程師標準>>> 今天把軟件工程里面關于面向對象的設計學完了,使我對面向對象OOA和OOD的思想有了進一步的認識,各科知識千溝萬壑,犬牙交錯,的確是這樣,能蒙住自己眼的永遠是你自己,而不是這個世界,因為美就在那里;裹住自己雙足的的永遠是…

macos安裝vscode_如何使用VSCode進行PostgreSQL開發及調試

Visual Studio Code (VSCode)是一個輕量級但功能強大的源代碼編輯器,可在桌面上運行,適用于Windows,macOS和Linux。 它內置了對JavaScript,TypeScript和Node.js的支持,并具有豐富的其他語言(如C,C&#xff…

最小生成樹 kruskal_使用Kruskal算法求解Java最小生成樹問題

最小生成樹 kruskalIn Electronic Circuit we often required less wiring to connect pins together. We can model this wiring problem with a connected, undirected graph G(V, E), where V is the set of pins, E is the set of possible interconnections between pair …

mysql數據庫面試題 軟件測試_軟件測試數據庫面試題一

前提本次分享只局限于 sql server 和 mysql 這兩種數據庫,其他數據庫暫不總結正文1. 對查詢的字段進行去重(distinct)用法注意:1. distinct【查詢字段】,必須放在要查詢字段的開頭,即放在第一個參數;2. 只能在SELECT 語…

python數碼時鐘代碼_python時鐘的實現

from time importsleepimporttimeimportosclassClock(object):"""數字時鐘""" def __init__(self, hour0, minute0, second0):"""初始化方法 :param hour: 時 :param minute: 分 :param second: 秒"""self._hourh…

PHP頁面跳轉

本文轉載自:http://blog.sina.com.cn/s/blog_9a06890901014ol1.html PHP頁面跳轉一、header()函數 header函數中Location類型的標頭是一種特殊的header調用,常用來實現頁面跳轉 注意:1、location和“:”號間不能有空格,否則不會跳…

如何打印出給定尺寸的方格_打印給定號碼的表格| 8086微處理器

如何打印出給定尺寸的方格Problem statement: 問題陳述: Write an assembly language program in 8086 to print the table of a given integer. 在8086中編寫匯編語言程序以打印給定整數的表。 Assumptions: Suppose the inputted number is at memory location …

python自動更新excel數據_如何更新Excel數據?(刷新所有查詢)

我有一個帶有一些查詢的Excel xlsm文件。目前我每天打開它,點擊“數據”選項卡中的“全部刷新”命令。我希望這件事能自動完成。我用python編寫了一個腳本(我是python新手)。問題是,刷新數據并保存Excel文件后,刷新的數據不可見(我知道刷新工…

mongoDB 使用手冊

2019獨角獸企業重金招聘Python工程師標準>>> 1、基本操作db.AddUser(username,password) 添加用戶db.auth(usrename,password) 設置數據庫連接驗證db.cloneDataBase(fromhost) 從目標服務器克隆一個數據庫db.commandHelp(name) returns the help for the commanddb.…

android搜索框功能實現_巧用 Trie 樹,實現搜索引擎關鍵詞提示功能

來源 | 碼海責編 | Carol封圖 | CSDN 付費下載于視覺中國我們幾乎每天都在用搜索引擎搜索信息,相信大家肯定有注意過這樣一個細節:當輸入某個字符的時候,搜索引框底下會出現多個推薦詞,如下,輸入「python」后,底下會出…

Python | 從用戶輸入數據,保存到文件,讀取并打印

Here, we have to input the data from the user, to read the data from user, we use input() method, and then the input data we have to store in the file by using write() method and then by using read() method we can get the data. 在這里,我們必須從…

python語句print type 1234的輸出結果是_Python語句 print(type(1J))的輸出結果是

【填空題】遍歷輸出文件所有行。 fopen("d:\\r2.txt","r") while True: str print(str,end) if not str: break f.close()【單選題】執行下列 Python語句將產生的結果是( ) i1 if (i): print(True) else: print( False)【單選題】Python語句 print(type(1/…

qt5.9.0調試如何查看變量的值_深入了解 Java 調試

Bug(俗稱"八阿哥") 是軟件開發繞不過的一道坎,因此調試便成了每位程序員一項必備的核心技能。調試不僅有助于理解程序的運行流程,還能改進代碼質量,最終提高開發者解決問題的能力以及交付軟件的品質。本文旨在討論 Java 調試關鍵技…

python字符串轉浮點數_Python | 打印不同的值(整數,浮點數,字符串,布爾值)...

python字符串轉浮點數In the given example, we are printing different values like integer, float, string and Boolean using print() method in python. 在給定的示例中,我們使用python中的print()方法打印不同的值,例如整數,浮點數&…

(6) 如何用Apache POI操作Excel文件-----POI-3.10的一個和注解(comment)相關的另外一個bug...

如果POI-3.10往一個工作表(sheet)里面插入數據的話,需要注意了,其有一個不太被容易發現的bug。 被插入的工作表(sheet)里面的單元格沒有包含任何的注解(comment)的時候,插…

mysql下拉刷新加載數據_下拉刷新、加載數據功能

paging nick加載更多getData();varm0,n2;//m:button點擊次數 n:一次加載幾條數據$(.page-btn-nick).click(getData);functiongetData(){$.ajax(paging.html).then(function(response){//測試url寫本頁面varobj{developer:[{name:nick},{name:ljy},{name:xzl},{name:jeson},{nam…

mcq 隊列_人工智能邏輯才能問答(MCQ)

mcq 隊列1) Why do we want to implement the concept of Logic in an AI system? So that the agent can have decision making capabilitySo that the agent can think and act humanlySo that the agent can apply the logic for finding the solution to any particular p…

第三周作業!

1、列出當前系統上所有已經登錄的用戶的用戶名,注意:同一個用戶登錄多次,則只顯示一次即可。答:本題思路:先用who命令列出當前登陸的用戶信息,然后使用cut命令對字段進行分割,選出我們需要的字段…