【问题标题】:Can't read any data from mysql table but I can insert into it无法从 mysql 表中读取任何数据,但我可以插入其中
【发布时间】:2020-09-10 06:22:05
【问题描述】:

我正在使用 python mysql.connector 并且我能够插入到表中,并通过 DBeaver(数据库管理器)检查它并验证数据提交。但是,如果我尝试从表中读取/选择,我会得到“无”。我不确定我能从这里做什么。

我的代码:

import mysql.connector, config

# declare vars
cfg = config.Setting(config.argparser())
sql_username = cfg.get_setting('sql', 'username')
sql_password = cfg.get_setting('sql', 'password')
sql_host = cfg.get_setting('sql', 'host')
sql_db = cfg.get_setting('sql', 'db')
db_config = mysql.connector.connect(user=sql_username, password=sql_password, host=sql_host, database=sql_db)
cursor = db_config.cursor(buffered=True)
print(cursor.execute('SELECT "date_created", "date_due", "title", "completed"'
               'FROM remind;'))


# query function, checks for errors, returns result of query
# columns: id | date_created | date_due | title | completed
#
def insert(db_id: object, db_table: object, date_created: object, date_due: object, title: object,
           completed: object) -> object:
    try:
        stmt = ("INSERT INTO " + db_table +
                "(id, date_created, date_due, title, completed) "
                "VALUES (%(id)s, %(date_created)s, %(date_due)s, %(title)s, %(completed)s)")
        data = {
            'id': db_id,
            'date_created': date_created,
            'date_due': date_due,
            'title': title,
            'completed': completed
        }
        query_result = cursor.execute(stmt, data)
        db_config.commit()
    except mysql.connector.Error as err:
        query_result = ("Insert Query: Something went wrong: {}".format(err))
    return query_result

【问题讨论】:

    标签: python mysql mysql-connector


    【解决方案1】:

    cursor.execute() 将执行选择查询。返回类型为 None 表示执行通过

    如果您想查看结果,请尝试cursor.fetchall()。这会获取结果集中的所有行。

    cursor.execute('SELECT "date_created", "date_due", "title", "completed"'
                   'FROM remind;')
    resultSet = cursor.fetchall()
    for row in resultSet:
        print(row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      相关资源
      最近更新 更多