import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
public class Connected {
private Connection connect = null;
private PreparedStatement pstm = null;
private ResultSet resultSet = null;
public Connection getConnection() {// 獲得與 ORACLE 數據庫的連接
try {
Class.forName("oracle.jdbc.OracleDriver");
connect = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:ORCL8", "SYSTEM",
"We090805046");
// System.out.println("connect:" + connect);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connect;
}
public void ReleaseResource() {// 關閉連接 釋放資源
try {
if (resultSet != null)
resultSet.close();
if (pstm != null)
pstm.close();
if (connect != null)
connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean Insert(String year,String month,String day,String tem) throws ParseException {
//由於數據庫中存儲的是01代表一月,所以需要將1變爲01
boolean flag = true;
String sql="insert into tempt values(?,?)";
connect = getConnection();
if(month.length()==1)
month="0"+month;
if(day.length()==1)
day="0"+day;
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Date date=sdf.parse(year+month+day);
try {
pstm = connect.prepareStatement(sql);
pstm.setDate(1,new java.sql.Date(date.getTime()));
pstm.setInt(2, Integer.parseInt(tem));
resultSet = pstm.executeQuery();
if (resultSet.next())
flag = true;
else
flag = false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ReleaseResource();//釋放資源
}
return flag;
}
}
在上述代碼中,由於Orcalez中是使用01代表1月,所以需要將1變爲01存入數據庫中
在這裏通過SimpleDataFormat類進行格式化,然後生成Date對象來存儲格式化後的時間 比如19961223或者19960101
在上圖的第五行中,由於數據庫中使用的Date類型屬於sql包下,與之前在util包下的date類並不一樣
所以通過sql.Date的構造方法傳入date對象的毫秒值,生成一個符合數據庫需求的對象,這樣才能進行存儲
那麼在讀取Date型數據的時候,只需要通過ResultSet類中的gatDate方法即可獲得,注意該方法返回的是一個util包下的Date對象