在django项目外,使用django.db链接数据库(postgres)

要用python链接到数据库,又不想写太多代码。想到了django,就偷懒了下。用django.db直连。

 

django版本:1.6.5 (1.5以后可以用以下代码)

#coding=utf-8

__author__ = 'tommy.yu'



from django.db import connection

from django.conf import settings

"""

settings.configure(

        ENGINE ='django.db.backends.postgresql_psycopg2',

        NAME='django',

        USER='django',

        PASSWORD='1',

        HOST='localhost',

        PORT='5432',

        )

"""



settings.configure(

    DATABASES = { 'default': {

        'ENGINE': 'django.db.backends.postgresql_psycopg2',

        'NAME': 'YOUR_DB_NAME',

        'USER': 'YOUR_USER',

        'PASSWORD': 'YOUR_PASS',

        'HOST': 'YOUR_SERVER_IP',

        'PORT': 'YOUR_SERVER_PART',

        }, },

    TIME_ZONE = 'Hongkong'

)



class cursor(object):

    def __init__(self):

        self.cr =  connection.cursor()



    def query(self,sql):

        self.cr.execute(sql)

        res = self.cr.fetchall()

        self.cr.close()

        return res



    def un_query(self,sql):

        return self.cr.execute(sql)

"""

#测试代码

cr =cursor()

res = cr.query('select tablename from pg_tables')

print(res)

"""

 1.5 以前如此配置

settings.configure(

        ENGINE ='django.db.backends.postgresql_psycopg2',

        NAME='django',

        USER='django',

        PASSWORD='***',

        HOST='localhost',

        PORT='5432',

        )

  

你可能感兴趣的:(postgres)