【问题标题】:SQL get data as json or dictSQL 以 json 或 dict 形式获取数据
【发布时间】:2017-11-08 09:00:17
【问题描述】:

我在 sql 中有一个名为 products 的数据库,我希望将所有行作为字典或 json 获取。我看过一个例子 here 但是我如何传递用户名、密码和主机?

这是一个例子:

import json
import psycopg2


def db(database_name='products'):
    return psycopg2.connect(database=database_name)

def query_db(query, args=(), one=False):
    cur = db().cursor()
    cur.execute(query, args)
    r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
    cur.connection.close()
    return (r[0] if r else None) if one else r

my_query = query_db("SELECT * FROM main_prod WHERE id = 1")
print(my_query)

json_output = json.dumps(my_query)
print(json_output)

当我像这样使用它时,我收到了这个错误:

File "/home/alex/Documents/Proiecte/Python/bapp/venv/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: fe_sendauth: no password supplied

当我这样做时

import json
import psycopg2


def db(database_name='products', password='...', host='123.123.123.13', user='alex'):
    return psycopg2.connect(database=database_name, password=password, host=host, user=user)

def query_db(query, args=(), one=False):
    cur = db().cursor()
    cur.execute(query, args)
    r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
    cur.connection.close()
    return (r[0] if r else None) if one else r

my_query = query_db("SELECT * FROM main_prod WHERE id = 1")
print(my_query)

json_output = json.dumps(my_query)
print(json_output)

它不会打印任何东西,它只是保持睡眠状态。

我该怎么做?

【问题讨论】:

  • 这与 JSON 或将结果作为 dicts 获取绝对无关......
  • 但它与sql有关
  • 只有连接到 postgresql - 这也不是 SQL 问题。
  • 好吧,那我该怎么办呢?
  • 并且可能与连接到数据库没有任何关系,因为通过提供用户和密码的值似乎可以解决该问题。可以使用psql或其他客户端连接数据库吗?

标签: python postgresql


【解决方案1】:

试试这个:

import psycopg2
import json

def main():
    conn_string = "database_name='products', password='...', host='123.123.123.13', user='alex'"
    # print the connection string we will use to connect
    print "Connecting to database\n ->%s" % (conn_string)

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()

    # execute our Query
    cursor.execute("SELECT * FROM main_prod WHERE id = 1")

    # retrieve the records from the database
    records = cursor.fetchall()
    objects = [
        {
            'id': row.id,
        } for row in records
    ] # there you tell what data you want to return

    json_output = json.dumps(objects)
    print(json_output)

if __name__ == "__main__":
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多