Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

I know that TinyInt can be used with a PreparedStatement with setByte(int parameterIndex, byte x and I also know that Bit can 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?

like image 898
LOD121 Avatar asked Mar 10 '11 23:03

LOD121


People also ask

How do you set a boolean to true in MySQL?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).

Is there a Boolean data type in MySQL?

MySQL does not have a boolean (or bool) data type. Instead, it converts boolean values into integer data types (TINYINT). When you create a table with a boolean data type, MySQL outputs data as 0, if false, and 1, if true.

How do you declare a boolean variable in MySQL?

MySQL does not contain built-in Boolean or Bool data type. They provide a TINYINT data type instead of Boolean or Bool data types. MySQL considered value zero as false and non-zero value as true. If you want to use Boolean literals, use true or false that always evaluates to 0 and 1 value.

How do I add a boolean value to a database?

You can insert a boolean value using the INSERT statement: INSERT INTO testbool (sometext, is_checked) VALUES ('a', TRUE); INSERT INTO testbool (sometext, is_checked) VALUES ('b', FALSE); When you select a boolean value, it is displayed as either 't' or 'f'.


2 Answers

Boolean in MySQL is a synonym for TINYINT(1); Bit is, 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"?

like image 159
Ted Hopp Avatar answered Oct 30 '22 10:10

Ted Hopp


You seem to be assuming that you can't address MySQL's BOOL using JDBC's setBoolean - you can. As such, the best option is to declare the column as BOOL and 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.

like image 23
Jon Bright Avatar answered Oct 30 '22 10:10

Jon Bright