1. 程式人生 > >tinyint和int分別針對unsign和sign的儲存範圍

tinyint和int分別針對unsign和sign的儲存範圍

資料庫中存int和tinyint注意點

最小值 臨界值 臨界值 最大值 結果
unsigned tinyint 0 127 128 255 沒有問題
signed tinyint -128 0 127 沒有問題
unsigned int 0 2147483647 2147483648 4294967295 當值大於2147483648出現問題
signed int -2147483648 0 2147483647 沒有問題

結論通過java的rs.getInt(),2147483648和4294967295都有問題,所以只要unsign int超出2147483647都會有問題。

(當然如果你rs.getLong也是沒有問題的,因為java中Long的最大範圍為2^63-1,但是一般寫程式都是rs.getInt(),所以需要注意一下)。

解釋

Java中的Integer 原始碼:

public final class Integer extends Number implements Comparable<Integer> { /** * A constant holding the minimum value an {@code int} can * have, -2<sup>31</sup>. */
@Native public static final int   MIN_VALUE = 0x80000000; /** * A constant holding the maximum value an {@code int} can * have, 2<sup>31</sup>-1. */ @Native public static final int   MAX_VALUE = 0x7fffffff;//2147483647

所以超過2147483647會報錯。如下:

com.mysql.jdbc.exceptions.jdbc4.MySQLDataException: '2.147483648E9' in column '4' is outside valid range for the datatype INTEGER