試用PostgreSQL+psycopg2+SQLAlchemy

1.PostgreSQL

由於想添加個gis功能模塊,看django推薦gis用PostgreSQL數據庫,拿來試用下,安裝的時候有幾個注意的小問題。 html

1.To use the yum repository, you must first install the repository RPM. To do this, download the correct RPM from the repository RPM listing, and install it with commands like:

yum install http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm

2.Once this is done, you can proceed to install and update packages the same way as the ones included in the distribution.

yum install postgresql93-server postgresql93-contrib
service postgresql-9.3 initdb
chkconfig postgresql-9.3 on python

centos須要手動初始化下而後設置默認自啓動。 mysql

2.psycopg2

另外用psycopg2時也碰到幾個問題 web

下載問題不大,直接去http://initd.org/psycopg/download/下載tar包就行了,安裝的時候報了幾回錯。 sql

首先一個pg_cong問題,而後一個libpq問題。去看他文檔說了這麼幾點: shell


Psycopg is a C wrapper to the libpq PostgreSQL client library. To install it from sources you will need: 數據庫

  • A C compiler. django

  • The Python header files. They are usually installed in a package such as python-dev. A message such as error: Python.h: No such file or directory is an indication that the Python headers are missing. ubuntu

  • The libpq header files. They are usually installed in a package such as libpq-dev. If you get an error: libpq-fe.h: No such file or directory you are missing them. centos

  • The pg_config program: it is usually installed by the libpq-dev package but sometimes it is not in a PATHdirectory. Having it in the PATHgreatly streamlines the installation, so try runningpg_config --version: if it returns an error or an unexpected version number then locate the directory containing the pg_config shipped with the right libpq version (usually/usr/lib/postgresql/X.Y/bin/) and add it to the PATH:

    $ export PATH=/usr/lib/postgresql/X.Y/bin/:$PATH

    You only need it to compile and installpsycopg2, not for its regular usage.

Note

The libpq header files used to compilepsycopg2should match the version of the library linked at runtime. If you get errors about missing or mismatching libraries when importingpsycopg2check (e.g. using ldd) if the modulepsycopg2/_psycopg.sois linked to the rightlibpq.so.

1.第一個用find / -name pg_cong找到路徑,export到PATH裏

2.第二個,折騰了很久,centos裏面python-dev 是python-devel,另外libpq-dev叫libpqxx-deve!

我屮艸芔茻!尼瑪!

文檔介紹忒不清楚!坑爹了!

這樣就行了,yum install下,後面就一路順利了。

Dependencies Resolved

================================================================================
 Package                  Arch       Version                 Repository    Size
================================================================================
Installing:
 libpqxx                  i686       1:4.0.1-1.rhel6         pgdg93       189 k
 libpqxx-debuginfo        i686       1:4.0.1-1.rhel6         pgdg93       772 k
 libpqxx-devel            i686       1:4.0.1-1.rhel6         pgdg93        91 k
Installing for dependencies:
 postgresql93-devel       i686       9.3.3-1PGDG.rhel6       pgdg93       1.4 M

Transaction Summary
================================================================================
Install       4 Package(s)

3.sqlalchemy+postgreSQL

安裝完成以後, 系統中會多出一個名爲 postgres 的用戶, 這個用戶用於登陸數據庫. 但沒法直接用該用戶在 shell 或 xdm 中登陸, 須先用其它用戶登陸 shell, 而後su到該用戶. 先爲該用戶設置一下密碼

passwd postgres
再切換到該用戶
me@host :~ su postgres
Password :
postgres@host : /home/ me $
若是當時處在某個用戶的 home 目錄, 如 /home/me 下, 則命令行會彈出一行錯誤信息
could not change directory to "/home/me"
由於 postgres 這個用戶沒法讀取當前用戶的 home 目錄. 以爲討厭的話能夠
cd /
此時在命令行輸入指令進入 Postgres 交互環境
psql
psql  ( version number )
Type   "help"   for  help .

postgres =#   input instructions here

這樣會以 postgres 用戶身份登陸, 若是要輸入密碼就輸入剛纔爲 postgres 用戶設置的密碼.

PostgreSQL默認的超級管理員密碼是postgres
鏈接方法:psql -U postgres(注意,是大寫的-U)
默認密碼爲空
修改密碼的方法是,用psql登入管理:psql -U postgres
而後用這樣的命令來修改密碼:alter user postgres with password 'new password


這時 postgres 用戶至關於數據庫的根用戶, 就像 root 用戶之於 Linux 系統同樣, 直接讓應用程序使用 postgres 用戶是比較危險的. 下面新建一個用戶
postgres =#   CREATE USER quanpower WITH PASSWORD 'XXXXXX';
CREATE ROLE
固然 Postgres 是不區分大小寫的. 不過這裏 (包括下文) 中將以全大寫標明這些是關鍵字, 而小寫的部分是可替換的. 密碼須要用引號包圍起來.

而後再創建一個新數據庫, 並受權quanpower 這個用戶可使用該數據庫
postgres =#   CREATE DATABASE SmartLinkCloud;
CREATE DATABASE
postgres =#   GRANT ALL PRIVILEGES ON DATABASE SmartLinkCloud TO quanpower;
GRANT
這樣就差很少好了. 下面開始搞 Python 與 SQLAlchemy 部分.

若是上面每一個句子輸入以後沒回顯結果, 而且交互環境開頭變爲了postgres-#(注意 # 前是一個減號而非等號), 請查看一下句尾的分號是否漏掉了.

4.使用 SQLAlchemy 鏈接 Postgres

有關 SQLAlchemy 的基本使用請見 這裏.
編寫這樣一段 Python 代碼, 來測試 Postgres 數據庫鏈接是否可用
import  sqlalchemy  as  sqla
import  sqlalchemy . orm  as  sqlorm
from  sqlalchemy . ext . declarative  import  declarative_base  as  sqla_declarative_base

Base   =  sqla_declarative_base ()
engine  =  sqla . create_engine ( 'postgresql://psuer:qwerty@localhost:5432/mydb' ,  echo = True )

class   Artist ( Base ):
    __tablename__  =   'artist'
    artist_id  =  sqla . Column ( 'id' ,  sqla . Integer ,  primary_key = True )
    name  =  sqla . Column ( 'name' ,  sqla . String )

Base . metadata . bind  =  engine
Base . metadata . create_all ()

Session   =  sqlorm . scoped_session ( sqlorm . sessionmaker ( bind = engine ))

def  save_artist ():
    artist  =   Artist ( name = 'aki misawa' )
    session  =   Session ()
     try :
        session . add ( artist )
        session . flush ()
        session . commit ()
     finally :
        session . close ()

if  __name__  ==   '__main__' :
    save_artist ()
上面的鏈接 URI 構成爲
PROTOCOL : //USERNAME:PASSWORD@localhost:PORT/DATABASE_NAME
其中
  • PROTOCOL: 協議名, 使用 Postgres 則爲 postgres
  • USERNAME/PASSWORD: 用戶名, 即剛纔配置的 psuser
  • PORT: 端口, Postgres 默認端口爲 5432 (想知道怎麼修改端口請自行 Google)
  • DATABASE_NAME: 數據庫名, 即剛纔配置的 mydb
運行這一段代碼可能出現下面的問題
ImportError :   No   module  named psycopg2
能夠經過pip或easy_install安裝 psycopg2 模塊, 或自行下載安裝. 安裝過程當中可能出現編譯找不到 Python.h 的狀況, 這時須要先安裝 python-dev, 如 ubuntu 下使用
apt-get install python-dev
來安裝.

若是上述代碼運行一切順利, 控制檯應該輸出完整的建表跟增長數據的語句. 以後在 psql 交互環境中執行
postgres =#   \c mydb
You  are now connected to database  "mydb"   as  user  "postgres" .
這句將切換當前數據庫到 mydb, 注意末尾是沒有分號的. 而後看一下表裏是否有對應的數據
mydb =#   SELECT * FROM artist;
 id  |  name
----+-------------
   1   |  aki misawa
若是回顯如此, 那麼恭喜, 如今一切就緒了!

5.PostgreSQLMySQL命令比較

 

PostgreSQL

MySQL

服務啓動:
    1)#service postgresql start
    2)#/etc/init.d/postgresql start
    3)#su – postgresql
      $pg_ctl start
PostgreSQL的進程號:12101207

服務啓動:
    1)#service mysqld start
    2)#/etc/init.d/mysqld start
    3)#safe_mysqld&

 

MySQL的進程號爲1663

第一次進入數據庫:
    #su – postgres
    $createdb  (建名爲postgres的數據庫)
    $psql 

第一次進入數據庫:

     #mysql
     mysql>    (出現這個提示符說明成功)

建立用戶:(用戶Ajian,密碼:123)
    #su – postgres

$psql

=#create user ajian with password ‘123’

建立用戶:(用戶Ajian,密碼:123)
     #grant all privileges on *.* to ajian@"%" identified by "123"

 (注意:同還能夠分配權限,這裏是ALL)

建立數據庫(My)

    #su – postgres

$psql

=#create database My with owner = ajian template = template1 encoding=’UNICODE’;

建立數據庫(My)

     1)#mysql

     Mysql>create database My;

      2)#mysqladmin create My

查看用戶和數據庫:

    #su – postgres

$psql

    =#\l         (查看數據庫)
    =#\du        (查看用戶)

查看用戶和數據庫:

    1)#mysql

     Mysql>show databases;   (看數據庫)

      2)#mysqlshow

新建用戶登陸:

(首先修改配置文件)

# vi /var/lib/pgsql/data/pg_hba.conf(在最後加)

host all all 127.0.0.1 255.255.255.255 md5

再重啓服務:#service postgresql restart

登陸:#psql –h 127.0.0.1 –U ajian My

Password:

新建用戶登陸:

     1)#mysql –u ajian –p  (帶口令登陸)

     2)#mysql

      Mysql>use My;

     (不帶口令登陸通常用於本機)

建立表(employee)

=#create table employee(

(#employee_id int primary key,

(#name char(8),

(#sex char(2));

建立表:

 >create table employee(

->employee_id int primary key,

->name char(8),

->sex char(2));

查看錶:

    =#\dt

查看錶:

    >show tables;

查看錶的結構:

    =#\d employee

查看錶的結構:

    >sescribe employee;

向表中添加數據:

   =#insert into employee values

  -#(‘1’,’zhang’,’F’);

-#(‘2’,’chen’,’M’,);

向表中添加數據:

>insert into employee values

  ->(‘1’,’zhang’,’F’);

->(‘2’,’chen’,’M’,);

查看錶的數據:

  =#select * from emlpoyee

查看錶的數據:

>select * from emlpoyee;

建立索引(IN_employee)

=#create index IN_employee on employee(name);

查看索引:

=#\di

刪除索引:

=#drop index IN_employee on employee;

重建索引:

=#reindex table employee;(重建employee全部的)

=#reindex index IN_employee;(重建指定的)

建立索引(IN_employee)

1)>create index IN_employee on employee(name);

2)>alter table employee add index IN_employee(name);

查看索引:

>show index from employee;

刪除索引:

1)>drop index IN_employee on employee;

2)>alter table emlpoyee drop index IN_employee;

刪除表:

   =#drop table employee;

刪除表:

   >drop table employee;

刪除數據庫:(注意命令前面的標誌)

   1)=#drop database ajian;

   2)$dropdb ajian

刪除數據庫:(注意命令前面的標誌)

   1>drop database ajian;

   2)#mysqladmin drop ajian

 6.幾個報錯整理:

1>新建了database,及user後,且受權後

postgres =#   CREATE USER quanpower WITH PASSWORD 'XXXXXX';
CREATE ROLE

postgres =#   CREATE DATABASE SmartLinkCloud;
CREATE DATABASE
postgres =#   GRANT ALL PRIVILEGES ON DATABASE SmartLinkCloud TO quanpower;
GRANT

用psql -U quanpower -d SmartLinkCloud -h localhost登陸,報錯:

postgres Peer authentication failed for user 「quanpower」:


在配置以前需將postgresql的端口號5432在iptables下開放。

開放方法參考:http://blog.csdn.net/ivan820819/archive/2009/02/03/3860163.aspx

yum安裝postgresql後的安裝路徑爲:/var/lib/pgsql下,主要配置文件在其data文件夾下,進入data文件夾

一、修改postgresql.conf文件

若是想讓PostgreSQL監聽整個網絡的話,將listen_addresses前的#去掉,並將listen_addresses = 'localhost'改爲listen_addresses = '*'

二、修改pg_hba.conf

sudo vi /var/lib/pgsql/9.3/data/pg_hba.conf

這個文件最後有一個列表,它決定了分派了每個用戶的權限,以及認證方式。格式是「Type Database User Address Method」,要注意的是method最好寫md5。

在列表後追加一行:host    all         all         192.168.1.0/24        password

三、修改postgres用戶密碼:passwd postgres

四、暫時將pg_hba.conf中,本機的認證方式改成trust,切換當前用戶爲postgres:su postgres

五、用psql登陸PostgreSQL系統,「SELECT * FROM pg_shadow;」,發現這個表裏的postgres這個用戶根本尚未存儲密碼;因而,再「ALTER USER postgres PASSWORD '它的密碼';

六、重啓服務/etc/init.d/postgresql-9.3 restart,鏈接成功。

PS:

Q. I've installed Postgresql under Red Hat Enterprise Linux 5.x server. I've created username / password and database. But when I try to connect it via PHP or psql using following syntax:

psql -d myDb -U username -W

It gives me an error that read as follows:

psql: FATAL: Ident authentication failed for user "username"

How do I fix this error?

A. To fix this error open PostgreSQL client authentication configuration file /var/lib/pgsql/data/pg_hba.conf :
# vi /var/lib/pgsql/data/pg_hba.conf
This file controls:

  1. Which hosts are allowed to connect
  2. How clients are authenticated
  3. Which PostgreSQL user names they can use
  4. Which databases they can access

By default Postgresql uses IDENT-based authentication. All you have to do is allow username and password based authentication for your network or webserver. IDENT will never allow you to login via -U and -W options. Append following to allow login via localhost only:

local	all	all	trust
host	all	127.0.0.1/32	trust

Save and close the file. Restart Postgresql server: # service postgresql restart Now, you should able to login using following command: $ psql -d myDb -U username -W

相關文章
相關標籤/搜索