JDBC(三)——數據庫不同對象的操作

時間

java.util.Date
子類:java.sql.Date 表示年月日
子類:java.sql.Time 表示時分秒
子類:java.sql.Timestamp 表示年月日時分秒(時間戳)

定義:

//java.sql.Date
Date date = new Date(System.currentTimeMillis());//當前時間
//java.sql.Timestamp
Timestamp time = new Timestamp(System.currentTimeMillis());

操作:
數據庫中要比較日期時,需要自己將日期格式轉成long類型數據,再形成Date對象。

public long dateToLong(String dateStr){
	DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	long time = -1;
	try {
        time = format.parse(dateStr).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return time;
}

文本

CLOB(Character Large Object)

  • 用來儲存大量的文本數據
  • 通常以流的方式來處理。

Mysql中相關類型:

  • TINYTEXT 最大長度爲255(2^8 - 1)字符的Text列
  • TEXT 最大長度爲65535(2^16 - 1)字符的Text列
  • MEDIUMTEXT 最大長度爲16777215(2^24 - 1)字符的Text列
  • LONGTEXT 最大長度爲4GB(2^32 - 1)字符的Text列

在setClob()方法中,第二個參數是一個流。

getClob()得到Clob對象,Clob對象有getCharacterStream()方法獲得字符流。

二進制

二進制BLOB的用法和大文本字符CLOB的用法完全一樣(只要把CLOB改成BLOB)。

//存
ps = con.prepareStatement("insert into student(Name,head) value (?,?) ");
ps.setString(1,"王二狗");
ps.setBlob(2,new FileInputStream("d:/icon.jpg"));
ps.execute();

//取
ps = con.prepareStatement("select * from student where Name = ?");
ps.setString(1,"王二狗");

rs = ps.executeQuery();
while(rs.next()){
	Blob b = rs.getBlob("head");
	//需要定義輸入流
	is = b.getBinaryStream();
	//需要定義輸出流
	os = new FileOutputStream("d:/a.jpg");
	int temp = 0;
	while((temp = is.read()) != -1){
		os.write(temp);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章