【问题标题】:displaying data of table from database using python使用python从数据库中显示表的数据
【发布时间】:2023-03-14 14:45:02
【问题描述】:

我是 python 的新手,尝试使用下面给出的简单程序是一个我试图从表中获取数据并显示它的程序。安装了Python3.4和mysql.connector 2.0.4,在localhost中运行http://localhost:804/cgi-bin/ex7.py

它正在连接到数据库但不从表中获取数据

 #!"C:\python34\python.exe"
    import sys
    import mysql.connector
    print("Content-Type: text/html;charset=utf-8")
    print()
    conn = mysql.connector.connect(host='localhost',port='8051',
                                           database='example',
                                           user='root',
                                           password='tiger')
   cursor = conn.cursor()
 if conn.is_connected():
        print('Connected to MySQL database')
    cursor.execute(""" SELECT * FROM album """)
    for row in cursor:
        print (row[1])

它的输出为: 连接 MySQL 数据库

不打印表格中的数据 请指出哪里出错了

【问题讨论】:

  • 您缺少 cursor = conn.cursor() 部分。但是你不应该真正使用 mysql 连接器。您可以使用 sqlachemy 或 pip install MySQL-python。使用 MySQL-python 非常简单。在这个网址上,您有示例 zetcode.com/db/mysqlpython(搜索页面“在第一个示例中,我们将获取 MySQL 数据库的版本。”)
  • 包括 cursor = conn.cursor() ,它不会工作。很多人正在使用 mysql 连接器。所以我安装并尝试使用这个。我只能使用这个

标签: python mysql apache


【解决方案1】:

我认为你错过了这部分

conn = mysql.connector.MySQLConnection(host='localhost',port='8051',
                                       database='example',
                                       user='root',
                                       password='tiger')
cursor = conn.cursor()
if conn.is_connected():
    print('Connected to MySQL database')
cursor.execute(""" SELECT * FROM album """)
# fetch all of the rows from the query
data = cursor.fetchall ()

# print the rows
for row in data :
    print row[1]

【讨论】:

  • 实际上是相同的输出。如果我打印(光标),它给出的是'' MySQLCursor: SELECT * FROM album",for循环有什么问题
【解决方案2】:
import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost', database='example', user='root', password='tiger')
    sql_select_Query = "SELECT * FROM album"
    cursor = connection.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    print("Total number of rows in album is: ", cursor.rowcount)
    print("\nPrinting each album record")
    for row in records:
        print("Id = ", row[0], )
        print("Name = ", row[1], "\n")
        # print("Price  = ", row[2])
        # print("Purchase date  = ", row[3], "\n")
except Error as e:
    print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
    connection.close()
    cursor.close()
    print("MySQL connection is closed")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2019-04-08
    • 2019-09-05
    • 2011-11-09
    • 1970-01-01
    • 2018-04-11
    • 2020-03-31
    相关资源
    最近更新 更多