python - 将查询结果赋值给变量

标签 python postgresql psycopg2

<分区>

我有以下查询 cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'") 来计算相同地址 (192.168.1.1) 的次数出现在 list_table 表中。 addr是inet类型。

当我将查询分配给变量并打印其结果时,我得到 None:

res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
print res # None

获得这种东西的正确方法是什么?

最佳答案

您可以使用以下步骤使用 python 检索关系数据库的数据:

    #!/usr/bin/python
    # import the desired package
    import MySQLdb

    # Open database connection
    db = MySQLdb.connect(hostaddress,user,password,db_name)

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # execute SQL query using execute() method.
    cursor.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")

    # Fetch a single row using fetchone() method and store the result in a variable. 
    data = cursor.fetchone()

  #OR use fetchall() method to fetch multiple rows and store the result in a list variable. 
 data = cursor.fetchall()

    print data

    # disconnect from server
    db.close()

关于python - 将查询结果赋值给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532823/

相关文章:

linux - 如何将 PostgreSQL 数据库连接到 Google Cloud Compute Engine?

django - 运行 Django 的 syncdb 时 OSX 10.7.3 上的 Postgresql 套接字错误

python - flask 重定向后我有无效数据

sql - PostgreSQL 约束,在提交时检查,而不是更早

sql - 如何使用事件记录查询检查 Rails 5 中是否不存在记录?

json - 如何检查 Postgres 中是否存在 json 键?

python - 从按钮将数据输入到 Entry 小部件

python - pyzmq:套接字因 "ZMQError: Operation cannot be accomplished in current state"中断

python - 如何更改图像尺寸以使我的卷积算法正常工作

java - 提交和回滚在数据库中是如何工作的?