Java Type vs PostgreSQL Type (五) 整數型別之對應 -byte
byte and Byte:
測試Java Type: byte and Byte 時,首先在PostgreSQL 建立一張資料表。
資料表語法:
CREATE TABLE bytetypes
(
id serial NOT NULL,
"smallint" smallint,
smallint1 smallint,
CONSTRAINT bytetypes_pkey PRIMARY KEY (id)
)
程式原始碼:
JavaByteType.java:
package zasax.type.numbertypes.integertypes;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import zasax.conn.PostgreConnection;
/**
*
* @author YiCheng,Hsiao
*/
public class JavaByteType {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private String setSQL = "Insert into bytetypes (smallint, smallint1) values (?,?)";
private String getSQL = "select * from bytetypes";
public static void main(String[] args) {
JavaByteType jbt = new JavaByteType();
byte b = 127;
byte b1 = 0;
Byte b2 = 0;
jbt.setByteValue(b, b);
ResultSet rs = jbt.getByteValue();
try {
while (rs.next()) {
b1 = rs.getByte("smallint");
b2 = rs.getByte("smallint");
System.out.println(b1 + " " + b2);
}
} catch (SQLException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setByteValue(byte b1, Byte b2) {
PostgreConnection pc = new PostgreConnection();
try {
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(setSQL);
pstmt.setByte(1, b1);
pstmt.setByte(2, b2);
pstmt.execute();
pstmt.close();
conn.close();
} catch (IOException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ResultSet getByteValue() {
PostgreConnection pc = new PostgreConnection();
try {
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(getSQL);
this.rs = pstmt.executeQuery();
} catch (IOException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JavaByteType.class.getName()).log(Level.SEVERE, null, ex);
}
return rs;
}
}
實際測試程序:
儲存Byte值方式:
透過setByteValue(byte , Byte ) 這個方法,將傳入值byte b = 127分別指派給byte(基本型別),Byte(外覆類別)。再將這兩個變數分別存入PostgreSQL Type : smallint 的兩個欄位(smallint , smallint1)。傳入值在資料表上有呈現資料,表示傳入成功。
讀取Byte值方式:
經getByteValue()的方法,先透過executeQuery(),將SQL語法"select * from bytetypes"傳入資料庫查詢,回傳ResultSet指派給rs,再將rs回傳指派給main()區塊的ResultSet,而ResultSet保存著SQL查詢完後的資料表內容,再分別透過ResultSet將值傳回給byte b1,以及Byte b2,最後在印出結果127,127,為了確定印出值為資料庫所傳回的,在初始值上,將byte b1 = 0 , Byte b2 = 0,以作為驗證其結果。
整理表格如下:
Java Types | PostgreSQL Types | 特性 |
byte | smallint | 2 bytes,小範圍整數,-32768 到 +32767 |
Byte |
沒有留言:
張貼留言