0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java6でpostgreSQLに接続する

Last updated at Posted at 2018-07-27

JavaのJDBCでPosgreSQLに接続する一番簡単なサンプルです。古いシステムに携わることもあるのでメモとして投稿しておきます。

ResultSetは、汎用的なbeanオブジェクトにセットします。

JDBCはダウンロードして外部Jarの追加で追加しておきます。

JDBCダウンロードサイト

GenericBean.java
package sampleResultSet;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GenericBean {
	private List<ColumnMeta> columnMetas=new ArrayList<ColumnMeta>();
	private List<List<Object>> rows=new ArrayList<List<Object>>();

	public GenericBean(ResultSet rs) throws SQLException {

		ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        	ColumnMeta meta = new ColumnMeta();
        	meta.setColumnName(rsmd.getColumnName(i));
        	meta.setColumnType(rsmd.getColumnTypeName(i));
        	this.addColumnMeta(meta);
        }
        while (rs.next()) {
        	List<Object> row = new ArrayList<Object>();
        	int columnIndex = 0;
            for (String field : this.getColumnNames()) {
            	row.add(rs.getObject(field));
            	columnIndex++;
            }
            this.addRow(row);
        }
	}

	public List<ColumnMeta> getColumnMetas() {
		return columnMetas;
	}
	public void setColumnMetas(List<ColumnMeta> columnMetas) {
		this.columnMetas = columnMetas;
	}
	public List<List<Object>> getRows() {
		return rows;
	}
	public void setRows(List<List<Object>> rows) {
		this.rows = rows;
	}
	public void addColumnMeta(ColumnMeta metadata) {
		this.columnMetas.add(metadata);
	}
	public void addRow(List<Object> row) {
		this.rows.add(row);
	}
	public String[] getColumnNames() {
		List<String> list=new ArrayList<String>();
		for (ColumnMeta meta : this.getColumnMetas()) {
			list.add(meta.getColumnName());
		}
		return list.toArray(new String[list.size()]);
	}
	public String[] getColumnTypes() {
		List<String> list=new ArrayList<String>();
		for (ColumnMeta meta : this.getColumnMetas()) {
			list.add(meta.getColumnType());
		}
		return list.toArray(new String[list.size()]);
	}
}
package sampleResultSet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;


public class SampleConnect {

	public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // connection
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/sampledatabase","testuser", "testuser");
            statement = connection.createStatement();

            // executeQueryでpg_shadowを検索する。
            //※本番では、preparedstatementを使いましょう。
            resultSet = statement.executeQuery("SELECT * FROM pg_tables");

            // フィールド名を取得してListに格納
            GenericBean bean = new GenericBean(resultSet);

            System.out.println("columns :");
        	System.out.println(CommonUtils.join(",",(Object[])bean.getColumnNames()));
        	System.out.println("columnTypes :");
        	System.out.println(CommonUtils.join(",",(Object[])bean.getColumnTypes()));
        	System.out.println("data :");
            for (List<Object> row : bean.getRows()) {
            	System.out.println(CommonUtils.join(",",row));
            }

        } catch (SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} finally {
            //接続を切断する
            if (resultSet != null) {
                try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
            }
            if (statement != null) {
                try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
            }
            if (connection != null) {
                try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
            }
        }
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?