Java Type vs PostgreSQL Type (十) 浮點數型別之對應 -double
double and Double:
測試Java Types:double and Double時,首先建置一張資料表。
資料表語法:
CREATE TABLE doubletypes
(
"double" double precision,
double1 double precision,
id serial NOT NULL,
CONSTRAINT doubletypes_pkey PRIMARY KEY (id)
)
原始程式碼:
JavaDoubleType.java:
package zasax.type.numbertypes.doubletypes;
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 JavaDoubleType {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private String setSQL = "Insert into doubletypes (double,double1) values (?,?)";
private String getSQL = "select * from doubletypes";
public static void main(String[] args)
throws IOException, ClassNotFoundException, SQLException {
JavaDoubleType jdt = new JavaDoubleType();
double d1 = 0.0;
Double d2 = 0.0;
jdt.setDoubleValue(1000000.333555444, 1000000.333555444);
ResultSet rs = jdt.getDoubleValue();
while (rs.next()) {
d1 = rs.getDouble("double");
d2 = rs.getDouble("double1");
System.out.println(d1 + " " + d2);
}
}
public void setDoubleValue(double d1, Double d2)
throws IOException, ClassNotFoundException, SQLException {
PostgreConnection pc = new PostgreConnection();
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(setSQL);
pstmt.setDouble(1, d1);
pstmt.setDouble(2, d2);
pstmt.execute();
pstmt.close();
conn.close();
}
public ResultSet getDoubleValue()
throws IOException, ClassNotFoundException, SQLException {
PostgreConnection pc = new PostgreConnection();
this.conn = pc.getConnection();
this.pstmt = conn.prepareStatement(getSQL);
this.rs = pstmt.executeQuery();
return rs;
}
}
實際測試程序:
透過setDoubleValue(double , Double ) 這個方法,將傳入值1000000.333555444,1000000.333555444分別指派給double(基本型別),Double(外覆類別)。再將這兩個變數分別存入PostgreSQL Type : double precision的兩個欄位(double , double1)。傳入值在資料表上有呈現資料,表示傳入成功。
經getDoubleValue()的方法,先透過executeQuery(),將SQL語法"select * from doubletypes"傳入資料庫查詢,回傳ResultSet指派給rs,再將rs回傳指派給main()區塊的ResultSet,而ResultSet保存著SQL查詢完後的資料表內容,再分別透過ResultSet將值傳回給double d1,以及Double d2,最後在印出結1000000.333555444,1000000.333555444,為了確定印出值為資料庫所傳回的,在初始值上,將double d1 = 0.0 ,Double d2 = 0.0,以作為驗證其結果。
印出的結果:
整理表格如下:
Java Types | PostgreSQL Types | 特性 |
double | double precision | 8 bytes,變精度,不精確 15 位十進制數字精度 |
Double |
沒有留言:
張貼留言