package com.humbinal.cockroach;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author
 * @version V1.0
 * @description
 * @date 2017/10/31 12:47.
 */

public class HelloWorld {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            String url = "jdbc:postgresql://10.33.25.78:26257/bank?sslmode=disable";
            String user = "postgres";
            String password = "123456";
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("是否成功连接pg数据库" + connection);
            String sql = "select * from accounts";
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                ResultSetMetaData rsmd = resultSet.getMetaData();
                int columnCount = rsmd.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    System.out.print(resultSet.getObject(i + 1).toString() + "\t");
                }
                System.out.print("\n");
            }

            try {
                // Create the "accounts" table.
                connection.createStatement().execute("CREATE TABLE IF NOT EXISTS people (id INT PRIMARY KEY, name STRING)");

                // Insert two rows into the "accounts" table.
                connection.createStatement().execute("INSERT INTO people (id, name) VALUES (1, '李四'), (2, '张三')");

                // Print out the balances.
                System.out.println("Initial balances:");
                ResultSet res = connection.createStatement().executeQuery("SELECT id, name FROM people");
                while (res.next()) {
                    System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getString("name"));
                }
            } finally {
                // Close the database connection.
                connection.close();
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
