使用 Java 连接数据库的 MySQL 中布尔值的最佳实现是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5267407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:19:34  来源:igfitidea点击:

What is the best implementation for boolean in MySQL using Java to connect to the database?

javamysqlboolean

提问by LOD121

I currently have a MySQL database set up with a Java client accessing and using the database. I need a Boolean data type in the database to determine whether some actions are allowed by various users of the database. What is the best implementation of Boolean that you can use in MySQL since there is no Boolean data type?

我目前有一个 MySQL 数据库,它设置了一个 Java 客户端访问和使用该数据库。我需要数据库中的布尔数据类型来确定数据库的各个用户是否允许某些操作。由于没有布尔数据类型,您可以在 MySQL 中使用的最佳布尔实现是什么?

I know that TinyIntcan be used with a PreparedStatementwith setByte(int parameterIndex, byte xand I also know that Bitcan also be used with setBoolean(int parameterIndex, boolean x). Which of these is the better solution for a Boolean value? And if there is a better solution, what would it be?

我知道TinyInt可以与 with 一起PreparedStatement使用setByte(int parameterIndex, byte x,我也知道Bit也可以与setBoolean(int parameterIndex, boolean x). 以下哪个是布尔值的更好解决方案?如果有更好的解决方案,那会是什么?

采纳答案by Ted Hopp

Booleanin MySQL is a synonym for TINYINT(1); Bitis, as well, if the number of bits is small enough. From the point of view of MySQL operation, it makes little difference which you use. What do you mean by "better"?

Boolean在 MySQL 中是TINYINT(1);的同义词。Bit如果位数足够小,也是如此。从 MySQL 操作的角度来看,您使用的几乎没有区别。你所说的“更好”是什么意思?

回答by Jon Bright

You seem to be assuming that you can't address MySQL's BOOLusing JDBC's setBoolean- you can. As such, the best option is to declare the column as BOOLand use setBoolean. Even though MySQL will alias your declaration to a TINYINT, your SQL declares what you want to use and your Java code makes it obvious at that level too.

您似乎在假设您无法BOOL使用 JDBC解决 MySQL的问题setBoolean——您可以。因此,最好的选择是将列声明为BOOL并使用setBoolean. 尽管 MySQL 会将您的声明别名为 a TINYINT,但您的 SQL 声明了您想要使用的内容,并且您的 Java 代码在该级别也很明显。