Python 3 - 查询Postgres数据库并处理结果
我刚开始学习编程,想做一个程序,从Postgres数据库中提取数据,稍微处理一下,然后通过短信发送这些数据。使用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 个回答
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
当然,你可以用更简洁的方式来写,不需要那个额外的变量:
phone = re.sub(r'[^\d]', '', result[1])
如果你想把它转换成数字类型,可以使用 int()
:
phone = int(re.sub(r'[^\d]', '', result[1]))