DBからデータを取得してJTable内に表示する

戻る



::::::::::::::
CommonQueryManager.java
::::::::::::::
import java.sql.*;
import java.util.*;
import java.io.*;

import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.*;

/**
* $Id: JTableTest.html,v 1.1 2009/06/22 16:11:48 kishi Exp kishi $ 
* @author KISHI Yasuhiro
*/

public class CommonQueryManager {

    private List resultList = null;
    private java.sql.Connection connection = null;

    public CommonQueryManager() {
        connection = ( new ConnectionManager() ).getConnection();
    }

    public List query( String sql, Object[] param ) {
        try {
            QueryRunner runner = new QueryRunner();
            ResultSetHandler handler = new MapListHandler();

            /* 結果をリストにして返す */
            if ( param == null ) {
                resultList = ( List ) runner.query( connection, sql, handler );
            } else {
                resultList = ( List ) runner.query( connection, sql, param, handler );
            }

        } catch ( Exception e ) {
            e.printStackTrace();
        }

        return resultList;
    }

    public void cleanUp() {
        try {
            DbUtils.close( connection );
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            if ( connection != null ) {
                connection = null;
            }
        }
    }

    /**
    * Usage: java -cp ../lib/commons-dbutils-1.0.jar\;. CommonQueryManager
    */
    public static void main( String[] args ) {


        CommonQueryManager manager = new CommonQueryManager();

        //------------------------------------------------------------------------------------
        // List resultList = manager.query("select * from dummy", null );
        //------------------------------------------------------------------------------------

        //------------------------------------------------------------------------------------
        // Object[] param = new Object[1];
        // param[0] = new Integer(6);
        // List resultList = manager.query("select * from dummy where id > ?", param );
        //------------------------------------------------------------------------------------

        Object[] param = new Object[ 2 ];
        param[ 0 ] = new Integer( 11 );
        param[ 1 ] = "名無し%";
        List resultList = manager.query( "select * from dummy where id > ? and name like ?", param );

        System.out.println( "レコード数=" + resultList.size() + "\n" );

        for ( int i = 0; i < resultList.size() ; i++ ) {
            // リスト内の各行を取り出す
            Map rec = ( Map ) resultList.get( i );

            // MAPインタフェースでカラムの値を取り出す。キーはcase sensitiveではない=大文字小文字無視
            System.out.println(
                rec.get( "id" )
                + "\t"
                + rec.get( "name" )
                + "\t"
                + rec.get( "updateTime" )
            );
        }

        manager.cleanUp();
    }
}

::::::::::::::
CommonUpdateManager.java
::::::::::::::
import java.sql.*;
import java.util.*;
import java.io.*;

import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.*;

/**
* $Id: JTableTest.html,v 1.1 2009/06/22 16:11:48 kishi Exp kishi $ 
* @author KISHI Yasuhiro
*/

public class CommonUpdateManager {

    private java.sql.Connection connection = null;

    public CommonUpdateManager() {
        connection = ( new ConnectionManager() ).getConnection();
    }

    public int update( String sql, Object[] param ) {
        int updateCount = 0;

        try {
            QueryRunner runner = new QueryRunner();

            if ( param == null ) {
                updateCount = runner.update( connection, sql );
            } else {
                updateCount = runner.update( connection, sql, param );
            }

        } catch ( Exception e ) {
            e.printStackTrace();
        }

        return updateCount;

    }

    public void cleanUp() {
        try {
            DbUtils.close( connection );
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            if ( connection != null ) {
                connection = null;
            }
        }
    }

    /**
    * Usage: java -cp ../lib/commons-dbutils-1.0.jar\;. CommonUpdateManager
    */
    public static void main( String[] args ) {

        int updateCount;

        CommonUpdateManager manager = new CommonUpdateManager();

        // updateCount = manager.update("insert into dummy ( name, updateTime) values ('おおお', '2005-1-1')", null);

        Object[] param = new Object[ 2 ];
        param[ 0 ] = "2006-1-22";
        param[ 1 ] = "名無し%";
        updateCount = manager.update( "update dummy set updateTime = ? where name like ?", param );

        manager.cleanUp();
    }
}

::::::::::::::
ConnectionManager.java
::::::::::::::
import java.io.*;
import java.util.*;
import java.sql.*;

/**
$Id: JTableTest.html,v 1.1 2009/06/22 16:11:48 kishi Exp kishi $
@author KISHI Yasuhiro
*/

public class ConnectionManager {

    /** XMLで記述されたプロパティファイル */
    private final String PROP_XML = "../conf/prop.xml";

    private java.sql.Connection connection = null;

    public ConnectionManager() {
        init();
    }

    // データベースの接続設定のメソッドを実装しておく
    public void init() {

        String JDBC_DRIVER = null;
        String JDBC_URL = null;
        String USERID = null;
        String PASSWORD = null;

        Properties prop = new Properties();
        try {
            InputStream stream = new FileInputStream( PROP_XML );
            prop.loadFromXML( stream );
            stream.close();

            JDBC_DRIVER = prop.getProperty( "JDBC_DRIVER" );
            JDBC_URL = prop.getProperty( "JDBC_URL" );
            USERID = prop.getProperty( "USERID" );
            PASSWORD = prop.getProperty( "PASSWORD" );

        } catch ( IOException e ) {
            e.printStackTrace();
        }

        // コネクションを取得
        try {
            Class.forName( JDBC_DRIVER );
            connection = DriverManager.getConnection( JDBC_URL, USERID, PASSWORD );
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        //-------------------------------------------------------------------
        // 設定ファイルを読み取りコネクションを取得するところまで実装する
        //-------------------------------------------------------------------
    }

    /**
    * コネクションを返す
    */
    public java.sql.Connection getConnection() {
        return connection;
    }
}
::::::::::::::
JTableTest.java
::::::::::::::
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.*;

import java.util.*;

/**
* $Id: JTableTest.html,v 1.1 2009/06/22 16:11:48 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class JTableTest extends JFrame implements ActionListener {

    private String[] columnNames = {"id", "name", "updateTime"};

    private DefaultTableModel model;

    public static void main( String[] args ) {
        JTableTest test = new JTableTest();

        /* 終了処理 */
        test.addWindowListener( new WindowAdapter() {
                                    public void windowClosing( WindowEvent e ) {
                                        System.exit( 0 );
                                    }
                                }
                              );

        test.setTitle( "DBからデータを取得して表示する" );
        test.setBounds( 10, 10, 480, 600 );

        test.setVisible( true );
    }

    public JTableTest() {

        model = new DefaultTableModel();
        // ヘッダをセット
        model.setColumnIdentifiers( columnNames );
        // DBからデータを取得
        getTableData();

        JTable table = new JTable( model );

        // スクロールペイン
        JScrollPane scrPane = new JScrollPane();
        scrPane.getViewport().setView( table );
        scrPane.setPreferredSize( new Dimension( 400, 500 ) );

        // 上部のパネル
        JPanel panel = new JPanel();
        panel.add( scrPane );

        // ボタン
        JButton reload = new JButton( "RELOAD" );
        reload.setActionCommand( "RELOAD" );
        reload.addActionListener( this );

        // 下部のパネル
        JPanel lowerPanel = new JPanel();
        lowerPanel.add( reload );

        // 全体
        Container content = this.getContentPane();
        content.add( panel, BorderLayout.CENTER );
        content.add( lowerPanel, BorderLayout.SOUTH );
    }

    public void actionPerformed( ActionEvent e ) {
        String command = e.getActionCommand();

        System.out.println( "COMMAND=" + command );
        if ( "RELOAD".equals( command ) ) {
            getTableData();
        }

    }

    private void getTableData() {
        // truncateする
        model.setRowCount( 0 );

        CommonQueryManager manager = new CommonQueryManager();
        java.util.List resultList = manager.query( "select * from dummy", null );

        for ( int i = 0; i < resultList.size() ; i++ ) {
            // リスト内の各行を取り出す
            Map rec = ( Map ) resultList.get( i );

            // MAPインタフェースでカラムの値を取り出す。キーはcase sensitiveではない=大文字小文字無視
            System.out.println(
                rec.get( "id" )
                + "\t"
                + rec.get( "name" )
                + "\t"
                + rec.get( "updateTime" )
            );

            Object[] obj = new Object[ 3 ];
            obj[ 0 ] = rec.get( "id" );
            obj[ 1 ] = rec.get( "name" );
            obj[ 2 ] = rec.get( "updateTime" );

            model.addRow( obj );
        }

        manager.cleanUp();

    }
}

戻る inserted by FC2 system