學習了下python調用PostgreSQL數據庫,PostgreSQL介紹網址如下
https://www.postgresql.org/docs/9.4/static/app-psql.html
psycopg2庫下載地址如下:
https://pypi.python.org/pypi/psycopg2
下載解壓后terminal cd到解壓目錄下輸入
sudo python setup.py install
后會報錯 Error: pg_config executable not found
參考http://blog.csdn.net/muzilanlan/article/details/50421693解決方法
- 安裝postgresql, 輸入
brew install postgresql
-
mac系統下默認下載路徑是 /usr/local/Cellar/postgresql/9.X.X/bin
其中9.X.X根據下載的版本不一樣 可以利用下圖中Finder中的前往文件夾功能找到postgresql文件目錄,確認下本機中的上述目錄
1.png 修改.bash_profile
.bash_profile 如果存在 則目錄可以在terminal中輸入cd~到主目錄 輸入pwd查詢到具體地址利用上述前往文件夾的方法找到,利用vim或者sublime打開
添加
PATH="/usr/local/Cellar/postgresql/9.X.X/bin:${PATH}"
export PATH
保存,若沒有該文件,可以建立一個加入上述代碼
- 回到安裝目錄輸入
sudo python setup.py install
可以成功安裝
psycopg2使用語法比較簡單,需要注意連接數據庫
DB = psycopg2.connect("dbname=forum")
參數需要輸入dbname =
sql的關鍵字需要大寫,例如
c = DB.cursor()
c.execute("SELECT a,b FROM xxx ORDER BY a DESC;")
cursor.execute("select name, weight from players,(select avg(weight) as av from players) as subq where weight < av;")