试用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

相关文章
相关标签/搜索