【问题标题】:How to put logs into mysql table?如何将日志放入mysql表?
【发布时间】:2023-03-25 09:47:02
【问题描述】:

我想将我的日志保存在 mysql 数据库中。所以我创建了这个函数来放入一个字符串,然后该函数将字符串格式化为 sql 注入并执行它。但总是失败。

我的桌子:

功能:

def log(string):
    sqlFormula = f'INSERT INTO logs (log) VALUES (%s)'
    string = f'({string})'
    mycursor.execute(sqlFormula, string)
    mydb.commit()

【问题讨论】:

  • 总是失败是什么意思?失败怎么办?

标签: python mysql sql


【解决方案1】:

execute 函数接受一个元组,但您正在创建一个带括号的字符串。这不是一回事。

改为:

def log(string):
    sqlFormula = 'INSERT INTO logs (log) VALUES (%s)'
    mycursor.execute(sqlFormula, (string,))
    mydb.commit()

更好的是,放弃那个无用的一次性变量:

def log(string):
    mycursor.execute('INSERT INTO logs (log) VALUES (%s)', (string,))
    mydb.commit()

【讨论】:

    【解决方案2】:

    mycursor.execute() 的第二个参数应该是列表或元组,而不是字符串。您可以通过在变量周围加上括号来创建一个元组,如果它只是一个元素,则添加一个逗号,而不是通过创建一个包含括号的字符串。

    def log(string):
        sqlFormula = f'INSERT INTO logs (log) VALUES (%s)'
        mycursor.execute(sqlFormula, (string,))
        mydb.commit
    

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2016-05-05
      • 2019-11-30
      相关资源
      最近更新 更多