Pleiades Eclipse 4.7 Oxygen : SWT(Table) + MySQL の SQL(SELECT) で一覧表示



WindowBuilder のインストール

SWT と Swing に関しては、WindowBuilder のサイト よりインストール用の URL を取得します。

※ バージョンは、WindowBuilder のバージョンです。(Eclipse のバージョンに依存しなくなりました)

この URL を『新規ソフトウェアのインストール』で表示されるダイアログに入力します


以前の WindowBuilder のアンインストールは、『ヘルプメニュー』>『Eclipse について』>『インストール詳細』で表示されるウインドウからアンインストールします
プロジェクト作成 プロジェクトは専用のものを使いますので、『その他』から以下を選択して下さい。 プロジェクトを作成したら、CTRL+N でその他より、以下を選択して下さい。 実行してウインドウが表示されたら準備完了です。 テンプレートの修正 メニューバー・タスクバー・ツールバー用のテンプレートは邪魔なだけなので削除します。 MySQL 接続用ライブラリのインストール Download Connector/J から jar をダウンロードして使用するか、Maven Repository より pom.xml に記述する内容を取得して使用します。 バージョンは、ここでは 5.1.46 を使用しています ( ダウンロードページでは、Looking for previous GA versions? リンクをクリックします ) Maven を使用するには、既存のプロジェクトを変換するのが簡単です。 ( プロジェクトを右クリックして『構成』から Maven プロジェクトへの変換 ) Chapter 4 Connector/J Examples 実行ソースコード
package mysql;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;
import com.mysql.jdbc.Statement;

public class Main extends ApplicationWindow {

	// https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Findex.html&org/eclipse/swt/widgets/Table.html
	private Table table;

	// https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.46
	// https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-examples.html
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private int maxRows = 20;

	public Main() {
		super(null);
		createActions();
	}

	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);

		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		table.setBounds(10, 41, 764, 338);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		Button button = new Button(container, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// 行を全て削除
				table.removeAll();
				loadMySQL("select * from 社員マスタ");
			}

		});
		button.setBounds(10, 10, 75, 25);
		button.setText("実行");

		return container;
	}

	private void createActions() {
		// Create the actions
	}

	public static void main(String args[]) {
		try {
			Main window = new Main();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("MySQL Connector/J");
	}

	@Override
	protected Point getInitialSize() {
		return new Point(800, 443);
	}


	private void loadMySQL( String sql ) {

		try {
			// MySQL Connector/J 接続
			conn = (Connection) DriverManager.getConnection(
				"jdbc:mysql://localhost/lightbox?user=root&password="
			);

			stmt = (Statement) conn.createStatement();
			rs = stmt.executeQuery(sql);

			// select の結果の列情報の取得
			ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();

			// 列数
			int columnCount = rsmd.getColumnCount();

			// 前回のテーブル列を全て削除
			int tableColumnCount = table.getColumnCount();
			TableColumn tableColumnWork = null;
			for( int i = tableColumnCount - 1; i >= 0; i--) {
				tableColumnWork = table.getColumn(i);
				tableColumnWork.dispose();
			}

			// 列名
			TableColumn tableColumn = null;
			for( int i = 1; i <= columnCount; i++) {
				tableColumn = new TableColumn(table, SWT.NONE);
				tableColumn.setWidth(100);
				tableColumn.setText(rsmd.getColumnName(i));
			}

			TableItem tableItem = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			int countRow = 0;
			while( rs.next() && countRow < maxRows ) {

				countRow++;

				String[] columnData = new String[columnCount];

				for( int i = 1; i <= columnCount; i++) {

					if ( rsmd.getColumnTypeName(i).equals("DATETIME") ) {
						columnData[i-1] = sdf.format(rs.getDate(i));
					}
					else {
						columnData[i-1] = rs.getString(i);
					}

				}
				tableItem = new TableItem(table, SWT.NONE);
				tableItem.setText(columnData);
			}

			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}

	}
}




pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MySQL_01</groupId>
  <artifactId>MySQL_01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
  </dependencies>

</project>


関連する記事

WindowBuilder のテーブルコントロールにインターネットから JSON データを読み込んで処理するテンプレート ( 行データをダブルクリックして取得 )