更新MySQL数据库表中的日期字段

0 投票
1 回答
588 浏览
提问于 2025-04-18 17:06

我无法在MySql数据库中更新日期字段。以下是我使用的代码:

def update_date(self):
    self.cursor.execute("""SELECT  min(date),rec_id FROM mytable1 GROUP BY rec_id;""")
    data=self.cursor.fetchall()
    for row in data:
        open_dt=row[0]
        pr_id=row[1]
        if open_dt:
            open_dt= open_dt.date()
            print open_dt,pr_id
            self.cursor.execute("""UPDATE mytable2 rec_open_date=%s WHERE rec_id=%d;"""%(open_dt,rec_id))
        else:
            pass

我已经完成了所有必要的导入,数据库连接也正常。当我运行代码时,它会带着一个警告运行:

Warning: Out of range value for column 'rec_open_date' at row 1
  self.cursor.execute("""UPDATE mytable2 SET rec_open_date=%s WHERE rec_id=%d;""" %(open_dt,rec_id))

1 个回答

1

如果你查看一下文档,你会发现execute这个方法需要一个单独的数据参数,而不是用%来格式化字符串。

你可以试试:

self.cursor.execute("""UPDATE mytable2 rec_open_date=%s WHERE rec_id=%s""",
                    (open_dt, rec_id))

而你实际上执行的是这个

UPDATE mytable2 rec_open_date=2011-02-03 12:34:56 WHERE rec_id=1;

这不是一个有效的语句,但出于某种原因,它还是执行了。此外,使用%会有安全隐患,可能导致SQL注入攻击。

撰写回答