我是python的新手,尝试下面给出的简单程序是一个程序,我试图从表中获取数据并显示它。安装了Python3.4和mysql.connector 2.0.4,在localhost中运行display method caching
它正在连接数据库,但没有从表中获取数据
#!"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数据库
不从表中打印数据 请建议哪里出错了
答案 0 :(得分:2)
你错过了这部分我认为
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]
答案 1 :(得分:0)
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")