【问题标题】:Unable to fetch results from SQL to Python using mysql.connector无法使用 mysql.connector 从 SQL 获取结果到 Python
【发布时间】:2020-07-23 03:19:34
【问题描述】:

我正在尝试使用 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

这是查询正在数据库中存储行的确认。

【问题讨论】:

  • 您是否尝试过通过Workbench或mysqlsh之类的工具查询表;确保插入的记录存在?
  • 是的,记录存在于数据库中,只是没有显示在 python 中。
  • 伴侣...我不知道。我已经使用 1)我自己的数据集(CREATEINSERTSELECT)测试了这个场景; 2)您在 Jupyter Notebook 中的 exact 复制/粘贴代码(登录凭据除外),以及 3)您在控制台 iPython 中的 #2 中创建的表上的 SELECT 语句......它们都有效完美。你的代码很好!我赞成这个问题,以帮助引起一些关注。我不知道伙计……对不起。会有想法的。您能否更新您的问题以显示数据库中的记录

标签: python mysql mysql-python


【解决方案1】:

代码运行良好。问题似乎在mycursor.executemany(sql, oval) 行中,因为变量在上面定义为val。修复它应该会给你预期的输出。

【讨论】:

  • 同意以上。我自己也发现了这个。好电话。
  • 对不起那些家伙,这是一个错字。代码仍未执行
  • 您的控制台是否出现任何错误?您是否检查了 MySQL 表是否已使用数据库中的条目创建?
  • 不,我在控制台中没有收到任何错误,是的,我检查了 MySQL,表已创建并且条目存在。
猜你喜欢
  • 2023-03-23
  • 2019-05-01
  • 2020-06-29
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多