有客自远方来52 2024-04-21 23:43 采纳率: 15.3%
浏览 3
已结题

为什么会出现类型转换错误的问题?

以下是我的代码,我想实现日期增添天数,但为什么会出现数据转换错误的问题
数据库模块代码

def update(rbook: Rbook) -> int:
    """
    更新数据
    :param s_book:
    :return:
    """
    con = None
    try:
        con = dbUtil.getCon()
        cursor = con.cursor()
        # 更新数据
        sql = f"UPDATE borrow set returnDate= DATEADD(week,1,'returnDate='{rbook.returnDate}'') where bid='{rbook.bid}'"
        cursor.execute(sql)
        con.commit()
        return cursor.rowcount
    except Exception as e:
        print(f"更新数据时发生错误: {e}")
        if con is not None:
            con.rollback()
        return 0
    finally:
        dbUtil.closeCon(con)

功能实现代码

def update(self):
    time = self.timeInput.text()
    borrow2 = Rbook.my_construtor2(None, None, None, time)
    if borrowDao.add(borrow2) is not None:
        self.x = show_custom_message_box("系统提示", "借阅成功!")
        self.resetForm()
        self.initTable()
    else:
        self.x = show_custom_message_box("系统提示", "借阅失败!")

"Conversion failed when converting the varchar value '2024-04-26' to data type int

  • 写回答

3条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-04-21 23:43
    关注

    引自免费微信小程序:皆我百晓生

    在您提供的代码中,出现的类型转换错误是因为在SQL语句中尝试将字符串类型的日期(例如 '2024-04-26')与整数进行加法操作,这是不正确的。在SQL Server中,DATEADD函数用于向日期添加时间间隔,而它期望第一个参数是表示时间间隔的整数,第二个参数是时间单位,第三个参数才是要添加的时间。

    您的SQL语句看起来像是试图给returnDate字段增加一周,但在表达式中,您将returnDate作为字符串拼接了进去,这导致了错误。正确的方法应该是将字符串转换为日期,然后执行DATEADD函数。以下是修改后的代码:

    首先,修复数据库模块中的SQL语句:

    def update(rbook: Rbook) -> int:
        """
        更新数据
        :param r_book:
        :return:
        """
        con = None
        try:
            con = dbUtil.getCon()
            cursor = con.cursor()
            # 更新数据
            # 使用CONVERT函数将字符串转换为日期,再执行DATEADD
            sql = f"UPDATE borrow SET returnDate = DATEADD(week, 1, CONVERT(date, '{rbook.returnDate}', 120)) WHERE bid = '{rbook.bid}'"
            cursor.execute(sql)
            con.commit()
            return cursor.rowcount
        except Exception as e:
            print(f"更新数据时发生错误: {e}")
            if con is not None:
                con.rollback()
            return 0
        finally:
            dbUtil.closeCon(con)
    

    这里我们使用了CONVERT(date, '{rbook.returnDate}', 120)来将字符串转换为日期。其中,120是日期格式标识符,对应于ISO 8601格式(YYYY-MM-DD)。根据您的实际日期字符串格式,这个数字可能需要调整。

    接下来,确保在功能实现代码中传递正确的日期格式给Rbook类:

    from datetime import datetime
    
    def update(self):
        time = self.timeInput.text()
        # 将输入的字符串转换为datetime对象,然后再转换为字符串(保持相同格式)
        borrowed_date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        borrow2 = Rbook.my_constructor2(None, None, None, borrowed_date)
        if borrowDao.update(borrow2) is not None:
            self.x = show_custom_message_box("系统提示", "借阅成功!")
            self.resetForm()
            self.initTable()
        else:
            self.x = show_custom_message_box("系统提示", "借阅失败!")
    

    这段代码中,我们使用了datetime.strptime()函数从用户输入的字符串创建一个datetime对象,然后使用strftime()将其转换回相同的格式。这样,在传递给update方法时,日期将以正确的格式存储在borrowed_date变量中。

    现在,当调用borrowDao.update(borrow2)时,应该不会出现类型转换错误了。请确保您的数据库连接和相关库已正确设置。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月22日
  • 创建了问题 4月21日