【问题标题】:Python MariaDB cant select items from tablePython MariaDB 无法从表中选择项目
【发布时间】:2022-10-05 01:17:42
【问题描述】:

我目前正在尝试从我的 MariaDB 数据库中的表中读取数据,但是每当我运行代码时,它都会返回 None,就好像表是空的,但它不是。我使用了数据库提供的 SQL 命令。有任何想法吗?

import sys

import mariadb as mysql
from pwd import pwd


def main():
    try:
        dbase = mysql.connect(
            user="???",
            password=pwd,
            host="???",
            port=???,
            database="market"
        )
    except mysql.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
        sys.exit(1)
    print(dbase)
    cursor = dbase.cursor()
    products = cursor.execute("SELECT * FROM Products")
    print(products)


if 1 == 1:
    main()

【问题讨论】:

  • 此错误通常是由于连接到错误的服务器引起的
  • @nbk IP 和端口与我用来连接 PHPmyAdmin 服务器的相同,所以我认为这不是问题。
  • 可能是数据库市场,那是空的,它至少有表(我猜如果有问题你尝试了 try catch

标签: python mariadb


【解决方案1】:

根据 mariadb documentation,游标上的 execute 方法只执行语句。

要获得您感兴趣的结果,您可以使用fetchall、fetchone 或fetchmany 等方法之一。

例如:

cursor = dbase.cursor()
cursor.execute("SELECT * FROM Products")
products = cursor.fetchall()
print(products)

如果表Products 有三列:id、description 和quantity,则应该产生类似[(1, "product1", 54), (2, "product2", 33)] 的内容,以及两行

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 2018-01-04
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多