当前位置: 首页 > 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.sczhlp.com/news/716.html

相关文章:

  • Dify快速搭建问答系统
  • AGC050A AtCoder Jumper
  • 用 Python 构建可扩展的图像验证码识别模块
  • 带外安全更新深度解析:ATL漏洞与IE防御措施
  • 更多脚本详见csdn
  • 第三天
  • Golang基础笔记十五之sync
  • hot100 回溯算法
  • 7.28随笔
  • 外培总结
  • 7月28日
  • CodeBuddy IDE小试-单元测试篇
  • 《大道至简》
  • linux中常用的数值计算
  • 【问题】--Macbook相关问题
  • 软工作业day27
  • 2025.7.28 闲话:CF678E Another Sith Tournament 倒序状压 DP 的一点想法
  • 基础知识
  • java学习(大道至简读后感)
  • js基础第一天
  • 春训#1题解
  • 垃圾话1
  • 2025/7/28 总结
  • 7.27 周总结
  • 存贮电解液配方的二进制格式与解析它的010 Editor的模板
  • 读《大道至简——软件工程实践者的思想》有感
  • 动态规划
  • Wireshark入门指南:网络流量分析利器
  • 量子计算先驱David Schuster的二十年探索之路
  • SpringBoot中使用TOTP实现MFA(多因素认证) - Tom