import java.sql.*;
class ciapia{
static final String dbUrl = "jdbc:postgresql://localhost/postgres";
static final String dbUser = "postgres";
static final String dbPwd = "pgAdmin";
static Connection conn = null;
static int iCnt;
/******************************************************************
* 主処理
*/
public static void main(String[] sArg) {
if( dbLogin() ){
if( sArg.length>0 ){
dbIns( sArg[0] );
}
dbList();
dbLogout();
}
}
/******************************************************************
* DB接続処理
*/
public static boolean dbLogin(){
try{
conn = DriverManager.getConnection( dbUrl, dbUser, dbPwd );
}catch(Exception e ){
e.printStackTrace();
return(false);
}
return(true);
}
/******************************************************************
* データ登録処理
*/
public static boolean dbIns( String sMsg ){
try{
PreparedStatement ps = conn.prepareStatement(
"insert into 伝言板(伝言) values(?)" );
ps.setString( 1, sMsg );
iCnt = ps.executeUpdate();
ps.close();
}catch( Exception e ){
e.printStackTrace();
return(false);
}
return(true);
}
/******************************************************************
* データ抽出処理
*/
public static boolean dbList(){
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select * from 伝言板 order by 番号 desc limit 10;" );
while( rs.next() ){
System.out.println(
rs.getInt("番号") + ") "
+ rs.getTimestamp("登録日") + " > "
+ rs.getString("伝言") );
}
rs.close();
stmt.close();
}catch( Exception e ){
e.printStackTrace();
return(false);
}
return(true);
}
/******************************************************************
* DB切断処理
*/
public static boolean dbLogout(){
try{
if( conn != null ){
conn.close();
}
}catch( Exception e ){
e.printStackTrace();
return(false);
}
return(true);
}
} |