postgresql db函数不起作用_Python & PostgreSQL

本文介绍了如何使用Python连接和操作PostgreSQL数据库,包括创建数据库、导入数据、查询数据等步骤,重点讲解了连接数据库的函数和数据导入的方法。
摘要由CSDN通过智能技术生成

671ff77a7c23830b9d374a2ab520f6c6.png

本篇介绍用Python操作PostgreSQL数据,本文的参考教程是 PostgreSQL Python

Python中的PostgreSQL工具

根据官方的解释 Python - PostgreSQL wiki,建议使用psycopg2

连接数据库

  1. 首先,你要有一个数据库,所以使用以下SQL语句,创建一个名为suppliers的数据库,本文中的操作都是围绕这一数据库展开的。
CREATE DATABASE suppliers;

2. 在Python中连接数据库:

(1)最直接的办法,使用psycopg2中的connect函数

conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")

(2)另一种方法,把连接数据库时用到的参数都列出来 (效果同上)

conn = psycopg2.connect(host="localhost",database="suppliers", user="postgres", password="postgres")

这里涉及到的参数有:

  • database: the name of the database that you want to connect.
  • user: the username used to authenticate.
  • password: password used to authenticate.
  • host: database server address e.g., localhost or an IP address
  • port: the port number that defaults to 5432 if it is not provided.

(3)注意:还可以使用配置文件(configuration file ),这种好处是把所有的参数放在了一个文件里,查找和修改就比较方便了。

database.ini

[postgresql]
host=localhost
database=suppliers
user=postgres
password=postgres

3. 放在一起:connect代码块

首先写 config() 函数,这一函数会读取配置文件 database.ini 来获取文件中用于数据库连接的参数. 我们可以保存以下代码块在config.py文件中,以便之后的重复调用。

#!/usr/bin/python
from configparser import ConfigParser


def config(filename='database.ini', section='postgresql'):
    # create a parser
    parser = ConfigParser()
    # read config file
    parser.read(filename)

    # get section, default to postgresql
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    return db

接下来写 connect() 函数。这一函数用于连接数据库,在以下的代码块中,connect() 函数帮助我们连接到 suppliers 数据库,并且打印出PostgreSQL数据库的版本号.

#!/usr/bin/python
import psycopg2
from config import config # 这是上面的config()代码块,已经保存在config.py文件中

def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)
		
        #
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值