Java Type vs PostgreSQL Type (七) 整數型別之對應 -int
int and Integer:
測試Java Types: int and Integer時,首先先建立一張資料表。
資料表語法:
CREATE TABLE inttypes
(
"int" integer,
int1 integer,
id serial NOT NULL,
CONSTRAINT inttypes_pkey PRIMARY KEY (id)
)
原始程式碼:
JavaIntegerType.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 zasax.conn.PostgreConnection;
/**
*
* @author YiCheng,Hsiao
*/
public class JavaIntegerType {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private String setSQL = "Insert into inttypes (int,int1) values (?,?)";
private String getSQL = "select * from inttypes";
public static void main(String[] args)
throws IOException, ClassNotFoundException, SQLException {
JavaIntegerType jit = new JavaIntegerType();
int i1 = 0;
Integer i2 = 0;
jit.setIntegerValue(1234567, 7654321);
ResultSet rs = jit.getIntegerValue();
while (rs.next()) {
i1 = rs.getInt("int");
i2 = rs.getInt("int1");
System.out.println(i1 + " " + i2);
}
}
public void setIntegerValue(int i1, Integer i2)
throws IOException, ClassNotFoundException, SQLException {
PostgreConnection pc = new PostgreConnection();
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(setSQL);
pstmt.setInt(1, i1);
pstmt.setInt(2, i2);
pstmt.execute();
pstmt.close();
conn.close();
}
public ResultSet getIntegerValue()
throws IOException, ClassNotFoundException, SQLException {
PostgreConnection pc = new PostgreConnection();
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(getSQL);
this.rs = pstmt.executeQuery();
return rs;
}
}
實際測試程序:
透過setIntegerValue(int , Integer ) 這個方法,將傳入值1234567,7654321分別指派給int(基本型別),Integer(外覆類別)。再將這兩個變數分別存入PostgreSQL Type : integer 的兩個欄位(int , int1)。傳入值在資料表上有呈現資料,表示傳入成功。
經getIntegerValue()的方法,先透過executeQuery(),將SQL語法"select * from inttypes"傳入資料庫查詢,回傳ResultSet指派給rs,再將rs回傳指派給main()區塊的ResultSet,而ResultSet保存著SQL查詢完後的資料表內容,再分別透過ResultSet將值傳回給int i1,以及Integer i2,最後在印出結果1234567,7654321,為了確定印出值為資料庫所傳回的,在初始值上,將int i1 = 0 , Integer i2 = 0,以作為驗證其結果。
印出的結果:
Java Types | PostgreSQL Types | 特性 |
int | integer | 4 bytes,常用的整數,-2147483648 到 +2147483647 |
Integer |
沒有留言:
張貼留言