当前位置: 首页 > news >正文

记一个由tinyint类型引发的低级错误

帮朋友分担一些项目任务时遇到的一个问题:sql语句查出的结果,和 ORM 读取到的值居然不一致,一度让我怀疑是哪里序列化出问题了。
由于心想着赶紧整完吃饭,也没怎么看数据库表结构,一时没想到是类型的问题,调试了半天才注意到了字段的类型是tinyint(1),瞬间想给自己几巴掌......
不过之前只记得 tinyint(1) 在 mysql 中是作为 bool 类型(非零值为 true)的,能马上联想到是类型错误导致的,只是具体原因并不清楚。
在查阅了官方的一些资料后发现这并不是一个bug,但也没有具体解释为何这么设计,我猜是当时的历史遗留问题,也可能是设计缺陷,不过可以通过连接字符串添加 Treat Tiny As Boolean=false 的配置方式取消隐式转换。

引用原文链接:https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html#idm46095360188160

These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true:

mysql> SELECT IF(0, 'true', 'false');
+------------------------+
| IF(0, 'true', 'false') |
+------------------------+
| false                  |
+------------------------+mysql> SELECT IF(1, 'true', 'false');
+------------------------+
| IF(1, 'true', 'false') |
+------------------------+
| true                   |
+------------------------+mysql> SELECT IF(2, 'true', 'false');
+------------------------+
| IF(2, 'true', 'false') |
+------------------------+
| true                   |
+------------------------+

引用原文链接:https://bugs.mysql.com/bug.php?id=67381

[25 Oct 2012 20:36] Baskin Tapkan
Description:
TinyInt(1) data type for a column is translated as a Boolean in .NET POCO class and ADO.NET Entity framework

How to repeat:

  1. Create a table with a TINYINT(1) column type
  2. Using the MySQL.Data and MySQL.Data.Entity NuGet packages, create a ADO.NET Entity Data model
  3. Observe that the data type for the TINYINT(1) is now shown as "Boolean"
    [29 Jan 2013 23:33] Fernando Gonzalez.Sanchez
    Thanks for your report,

This is not actually a bug, you can add to your connection string
"Treat Tiny As Boolean=false;"

and now the tinyint will be interpreted like a type sbyte in C#.

http://www.vanclimg.com/news/746.html

相关文章:

  • 2025最新程序员面试题集合 包括各大厂面试规范,面试问题
  • 浅谈基环树
  • Day 28
  • 2025.7.28
  • 叔向贺贫
  • nest基础学习流程图
  • grabcad
  • 2025.7.28总结 - A
  • 亚马逊发布TEACh数据集训练家用机器人
  • 完全使用TRAE和AI 开发一款完整的应用----第一周
  • CentOS Stream 9上部署FTP应用服务的两种方法(传统安装和docker-compose)
  • SeuratExtend 可视化教程(1):单细胞分析的高颜值绘图指南
  • 机械运动
  • 【2025.7.28】模拟赛T4
  • 深度学习(onnx量化)
  • Redisson
  • uni-app项目跑APP报useStore报错
  • P13493 【MX-X14-T3】心电感应 题解
  • DE_aemmprty 草稿纸合集
  • 题解:P13308 故障
  • mmap提高LCD显示效率
  • 用 Python 构建可扩展的验证码识别系统
  • Java学习Day28
  • 在运维工作中,Dockerfile中常见指令有哪些?
  • 英语_阅读_Rivers are important in culture_单词_待读
  • 题解:P12151 【MX-X11-T5】「蓬莱人形 Round 1」俄罗斯方块
  • 在运维工作中,docker封闭了哪些资源?
  • SciTech-EECS-Library: img2pdf 与 pdf2image : Python 的 pdf 与 image 双向转换库
  • 深度学习(pytorch量化)
  • 在运维工作中,Docker怎么清理容器磁盘空间?