我正在尝试使用python查询存储在SQL中的表。我正在使用mysql.connector包执行任务。
import mysql.connector
#Creating a connection
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="something",
database='mydatabase',
)
print(mydb)
##Creating a table called customers
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
#Inserting records to the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345')]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
问题是当我查询数据库时,没有显示输出。
query=("SELECT name, address FROM customers")
mycursor.execute(query)
for (name, address) in mycursor:
print("{} {}".format(name, address))
这里是我尝试过的内容以及从中获取代码的链接。链接:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
代码运行正常。问题似乎出在mycursor.executemany(sql, oval)
行中,因为变量定义为上面的val
。修复该问题后,您会得到预期的输出。