パニック速報

The next stage is paradise…

JavaでDB接続マン

個人的覚書+エイ用

件数と気温と湿度の最小値と最大値と平均値を出力


import java.util.*;
import java.text.*;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Select2{
	public static void main(String[] args){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
	
		//SQL
		String sql = "select count(*) as cnt, max(temp) as tempMax,min(temp) as tempMin,max(humi) as humiMax,min(humi) as humiMin,avg(temp) as tempAvg,avg(humi) as humiAvg from Thdata";
		
		//JDBC
		try{
			// JDBCドライバの登録
			String driver = "com.mysql.jdbc.Driver";
			
                        // コネクションの取得
                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/THT","hit","hit");

			// 文字列からインスタンスを生成(よくわかんないw(単芝))
			Class.forName (driver);

	        // テーブル照会実行
	        Statement stmt = con.createStatement();
	        ResultSet rs = stmt.executeQuery (sql);

	        // テーブル照会結果を出力
	        while(rs.next()){
	           System.out.println("件数:" + rs.getInt("cnt"));
	           System.out.println("最高気温:" + rs.getInt("tempMax"));
	           System.out.println("最低気温:" + rs.getInt("tempMin"));
	           System.out.println("最高湿度:" + rs.getInt("humiMax"));
	           System.out.println("最低気温:" + rs.getInt("thumiMin"));
	           System.out.println("平均気温:" + rs.getInt("tempAvg"));
	           System.out.println("平均湿度:" + rs.getInt("humiAvg"));
	        }

	        // データベースのクローズ
	        rs.close();
	        stmt.close();
	        con.close();
	    } catch (SQLException e) {
	        System.err.println("SQL failed.");
	        e.printStackTrace ();
	    } catch (ClassNotFoundException ex) {
	        ex.printStackTrace ();
	    }
	}
}