首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python显示数据库中的表数据

问使用python显示数据库中的表数据
EN

Stack Overflow用户
提问于 2015-06-02 19:54:21
回答 2查看 18.8K关注 0票数 1

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

它正在连接到数据库,但没有从表中提取数据

代码语言:javascript
复制
 #!"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数据库

未打印表中的数据请指出错误所在

EN

回答 2

Stack Overflow用户

发布于 2015-06-02 19:59:43

我想你漏掉了这一部分

代码语言:javascript
复制
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]
票数 4
EN

Stack Overflow用户

发布于 2019-09-06 14:57:41

代码语言:javascript
复制
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")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30595367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档