Python 3 - 查询postgres db并操纵结果

时间:2014-03-04 17:33:09

标签: python postgresql sms

我是编程的新手。我正在尝试创建一个程序,它将从Postgres数据库中提取数据,对其进行一些格式化,然后通过SMS消息将数据推出。使用python 3,我可以连接并查询数据库,我也可以通过短信发送数据。这是我需要帮助的任务之中!

以下是我用于查询的精简代码:

import psycopg2

conn = psycopg2.connect("dbname='xxxxxxxxx' user='xxxxxxxx' host='xxxxxxxx' port='xxxxxx' password='xxxxxxxxx'")
cur = conn.cursor()
cur.execute("SELECT ......")

从这里开始,我可以使用cur.fetchall()cur.fetchone()查看结果。现在让我们假设我想对这个结果做点什么。例如,格式化它(可能是电话号码,我想删除所有非数字字符)。我该如何操纵这些数据?

如果这是一个愚蠢的问题我很抱歉,我刚刚开始编程!

1 个答案:

答案 0 :(得分:1)

cur.fetchall()cur.fetchone()返回元组(或fetchone()中的单个元组)您可以通过索引访问列值并将变量存储在变量中并像操纵它一样操作任何其他变量,您可以使用正则表达式去除非数字字符:

import psycopg2
import re

conn = psycopg2.connect("dbname='xxxxxxxxx' user='xxxxxxxx' host='xxxxxxxx' port='xxxxxx' password='xxxxxxxxx'")
cur = conn.cursor()
cur.execute("SELECT id, phone FROM table")

result = cur.fetchone()  # Fetch first result
str_phone = result[1]  # Get the 2nd column (phone) value

only_numbers = re.sub(r'[^\d]', '', str_phone)  # Strip non numeric chars

当然你可以用更紧凑的方式写这个,没有额外的var:

phone = re.sub(r'[^\d]', '', result[1])

并将其转换为int()的数字类型,如果这就是您的目标:

phone = int(re.sub(r'[^\d]', '', result[1]))