Example usage for java.sql DatabaseMetaData getUserName

List of usage examples for java.sql DatabaseMetaData getUserName

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getUserName.

Prototype

String getUserName() throws SQLException;

Source Link

Document

Retrieves the user name as known to this database.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();

    DatabaseMetaData mtdt = conn.getMetaData();
    System.out.println("URL in use: " + mtdt.getURL());
    System.out.println("User name: " + mtdt.getUserName());
    System.out.println("DBMS name: " + mtdt.getDatabaseProductName());
    System.out.println("DBMS version: " + mtdt.getDatabaseProductVersion());
    System.out.println("Driver name: " + mtdt.getDriverName());
    System.out.println("Driver version: " + mtdt.getDriverVersion());
    System.out.println("supp. SQL Keywords: " + mtdt.getSQLKeywords());

    conn.close();/*from  w  w w .j  a  v a2 s  . c o m*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();

    DatabaseMetaData md = conn.getMetaData();

    System.out.println("JDBC Driver: " + md.getDriverName() + " " + md.getDriverVersion());
    System.out.println("Database: " + md.getURL());
    System.out.println("User: " + md.getUserName());

    conn.close();/*w  ww  .j  a  va2 s.co  m*/
}

From source file:Main.java

public static void main(String[] argv) {
    Connection connection = null;
    Statement statement;/*www  .  j a va2 s .  co  m*/
    ResultSet rs;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        DatabaseMetaData md = connection.getMetaData();
        statement = connection.createStatement();

        System.out.println("getURL() - " + md.getURL());
        System.out.println("getUserName() - " + md.getUserName());
        System.out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion());
        System.out.println("getDriverMajorVersion - " + md.getDriverMajorVersion());
        System.out.println("getDriverMinorVersion - " + md.getDriverMinorVersion());
        System.out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh());

        System.out.println("<H1>Feature Support</H1>");
        System.out.println(
                "supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>");
        System.out.println("supportsBatchUpdates - " + md.supportsBatchUpdates());
        System.out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames());
        System.out.println("supportsPositionedDelete - " + md.supportsPositionedDelete());
        System.out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins());
        System.out.println("supportsStoredProcedures - " + md.supportsStoredProcedures());
        System.out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers());
        System.out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());
        System.out.println("getMaxRowSize - " + md.getMaxRowSize());
        System.out.println("getMaxStatementLength - " + md.getMaxStatementLength());
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxConnections - " + md.getMaxConnections());
        System.out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength());

        System.out.println("getTableTypes()");
        rs = md.getTableTypes();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        System.out.println("getTables()");
        rs = md.getTables("accounts", "", "%", new String[0]);
        while (rs.next()) {
            System.out.println(rs.getString("TABLE_NAME"));
        }
        System.out.println("Transaction Support");
        System.out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation());
        System.out
                .println("dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions());

        System.out.println("General Source Information");
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable());
        System.out.println("getTimeDateFunctions - " + md.getTimeDateFunctions());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());

        System.out.println("getTypeInfo()");
        rs = md.getTypeInfo();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:GetDBInfo.java

public static void main(String[] args) {
    Connection c = null; // The JDBC connection to the database server
    try {/* w  ww . j av  a 2 s.c  o m*/
        // Look for the properties file DB.props in the same directory as
        // this program. It will contain default values for the various
        // parameters needed to connect to a database
        Properties p = new Properties();
        try {
            p.load(GetDBInfo.class.getResourceAsStream("DB.props"));
        } catch (Exception e) {
        }

        // Get default values from the properties file
        String driver = p.getProperty("driver"); // Driver class name
        String server = p.getProperty("server", ""); // JDBC URL for server
        String user = p.getProperty("user", ""); // db user name
        String password = p.getProperty("password", ""); // db password

        // These variables don't have defaults
        String database = null; // The db name (appended to server URL)
        String table = null; // The optional name of a table in the db

        // Parse the command-line args to override the default values above
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-d"))
                driver = args[++i]; //-d <driver>
            else if (args[i].equals("-s"))
                server = args[++i];//-s <server>
            else if (args[i].equals("-u"))
                user = args[++i]; //-u <user>
            else if (args[i].equals("-p"))
                password = args[++i];
            else if (database == null)
                database = args[i]; // <dbname>
            else if (table == null)
                table = args[i]; // <table>
            else
                throw new IllegalArgumentException("Unknown argument: " + args[i]);
        }

        // Make sure that at least a server or a database were specified.
        // If not, we have no idea what to connect to, and cannot continue.
        if ((server.length() == 0) && (database.length() == 0))
            throw new IllegalArgumentException("No database specified.");

        // Load the db driver, if any was specified.
        if (driver != null)
            Class.forName(driver);

        // Now attempt to open a connection to the specified database on
        // the specified server, using the specified name and password
        c = DriverManager.getConnection(server + database, user, password);

        // Get the DatabaseMetaData object for the connection. This is the
        // object that will return us all the data we're interested in here
        DatabaseMetaData md = c.getMetaData();

        // Display information about the server, the driver, etc.
        System.out.println("DBMS: " + md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
        System.out.println("JDBC Driver: " + md.getDriverName() + " " + md.getDriverVersion());
        System.out.println("Database: " + md.getURL());
        System.out.println("User: " + md.getUserName());

        // Now, if the user did not specify a table, then display a list of
        // all tables defined in the named database. Note that tables are
        // returned in a ResultSet, just like query results are.
        if (table == null) {
            System.out.println("Tables:");
            ResultSet r = md.getTables("", "", "%", null);
            while (r.next())
                System.out.println("\t" + r.getString(3));
        }

        // Otherwise, list all columns of the specified table.
        // Again, information about the columns is returned in a ResultSet
        else {
            System.out.println("Columns of " + table + ": ");
            ResultSet r = md.getColumns("", "", table, "%");
            while (r.next())
                System.out.println("\t" + r.getString(4) + " : " + r.getString(6));
        }
    }
    // Print an error message if anything goes wrong.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println(((SQLException) e).getSQLState());
        System.err.println("Usage: java GetDBInfo [-d <driver] " + "[-s <dbserver>]\n"
                + "\t[-u <username>] [-p <password>] <dbname>");
    }
    // Always remember to close the Connection object when we're done!
    finally {
        try {
            c.close();
        } catch (Exception e) {
        }
    }
}

From source file:mangotiger.sql.SQL.java

private static String asString(final Connection connection) throws SQLException {
    final DatabaseMetaData metaData = connection.getMetaData();
    return metaData.getURL() + ":username=" + metaData.getUserName();
}

From source file:com.anyi.gp.license.RegisterTools.java

public static String getDBServerURL() {
    Connection conn = null;//from ww  w .  ja  v a 2s. c o  m
    try {
        conn = DAOFactory.getInstance().getConnection();
        if (conn != null) {
            DatabaseMetaData meta = conn.getMetaData();
            return (meta.getURL() + ":" + meta.getUserName()).toUpperCase();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DBHelper.closeConnection(conn);
    }
    return "";
}

From source file:com.aurel.track.dbase.UpdateDbSchema.java

private static boolean hasTables(Connection conn) {
    boolean hasTables = false;
    try {/*w w  w. jav a 2 s. c o  m*/
        DatabaseMetaData md = conn.getMetaData();
        String userName = md.getUserName();
        String url = md.getURL();
        boolean isOracleOrDb2 = url.startsWith("jdbc:oracle") || url.startsWith("jdbc:db2");
        ResultSet rsTables = md.getTables(conn.getCatalog(), isOracleOrDb2 ? userName : null, null, null);
        LOGGER.info("Getting the tables metadata");
        if (rsTables != null && rsTables.next()) {
            LOGGER.info("Find TSITE table...");

            while (rsTables.next()) {
                String tableName = rsTables.getString("TABLE_NAME");
                String tablenameUpperCase = tableName.toUpperCase();
                if ("TSITE".equals(tablenameUpperCase)) {
                    LOGGER.info("TSITE table found");
                    hasTables = true;
                    break;
                } else {
                    if (tablenameUpperCase.endsWith("TSITE")) {
                        LOGGER.info(tablenameUpperCase + " table found");
                        hasTables = true;
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (!hasTables) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT OBJECTID FROM TSITE");
            if (rs.next()) {
                hasTables = true;
            }
        } catch (SQLException e) {
            LOGGER.info("Table TSITE  does not exist");
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
        }
    }
    return hasTables;
}

From source file:fi.luontola.cqrshotel.JdbcConfiguration.java

@PostConstruct
public void statusReport() throws SQLException {
    try (Connection connection = DataSourceUtils.getConnection(dataSource)) {
        DatabaseMetaData metaData = connection.getMetaData();
        log.info("Database: {} {}", metaData.getDatabaseProductName(), metaData.getDatabaseProductVersion());
        log.info("User: {}", metaData.getUserName());
        log.info("Connection URL: {} (configuration was {})", metaData.getURL(), dataSourceProperties.getUrl());
        log.info("Flyway locations: {}", flywayProperties.getLocations());
    }//from w w w. j av a 2s.  co  m
}

From source file:DatabaseInfo.java

public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse)
        throws ServletException, IOException {

    PrintWriter out = null;/*  w  ww . j  a va  2  s. com*/
    Connection connection = null;
    Statement statement;
    ResultSet rs;

    outResponse.setContentType("text/html");
    out = outResponse.getWriter();

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        DatabaseMetaData md = connection.getMetaData();
        statement = connection.createStatement();

        out.println("<HTML><HEAD><TITLE>Database Server Information</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("<H1>General Source Information</H1>");
        out.println("getURL() - " + md.getURL() + "<BR>");
        out.println("getUserName() - " + md.getUserName() + "<BR>");
        out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion() + "<BR>");
        out.println("getDriverMajorVersion - " + md.getDriverMajorVersion() + "<BR>");
        out.println("getDriverMinorVersion - " + md.getDriverMinorVersion() + "<BR>");
        out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh() + "<BR>");

        out.println("<H1>Feature Support</H1>");
        out.println("supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>");
        out.println("supportsBatchUpdates - " + md.supportsBatchUpdates() + "<BR>");
        out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames() + "<BR>");
        out.println("supportsPositionedDelete - " + md.supportsPositionedDelete() + "<BR>");
        out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins() + "<BR>");
        out.println("supportsStoredProcedures - " + md.supportsStoredProcedures() + "<BR>");
        out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers() + "<BR>");
        out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL() + "<BR>");
        out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>");

        out.println("<H1>Data Source Limits</H1>");
        out.println("getMaxRowSize - " + md.getMaxRowSize() + "<BR>");
        out.println("getMaxStatementLength - " + md.getMaxStatementLength() + "<BR>");
        out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>");
        out.println("getMaxConnections - " + md.getMaxConnections() + "<BR>");
        out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength() + "<BR>");

        out.println("<H1>SQL Object Available</H1>");
        out.println("getTableTypes()<BR><UL>");
        rs = md.getTableTypes();
        while (rs.next()) {
            out.println("<LI>" + rs.getString(1));
        }
        out.println("</UL>");

        out.println("getTables()<BR><UL>");
        rs = md.getTables("accounts", "", "%", new String[0]);
        while (rs.next()) {
            out.println("<LI>" + rs.getString("TABLE_NAME"));
        }
        out.println("</UL>");

        out.println("<H1>Transaction Support</H1>");
        out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation() + "<BR>");
        out.println(
                "dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions() + "<BR>");

        out.println("<H1>General Source Information</H1>");
        out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>");
        out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable() + "<BR>");
        out.println("getTimeDateFunctions - " + md.getTimeDateFunctions() + "<BR>");
        out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>");

        out.println("getTypeInfo()<BR><UL>");
        rs = md.getTypeInfo();
        while (rs.next()) {
            out.println("<LI>" + rs.getString(1));
        }
        out.println("</UL>");

        out.println("</BODY></HTML>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.focusns.service.env.impl.EnvironmentServiceImpl.java

protected Environment lookupDB() {
    try {/*from  w  ww.j a  v  a 2s.c o  m*/
        DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
        //
        EnvironmentDB envDB = new EnvironmentDB();
        envDB.setDatabaseName(metaData.getDatabaseProductName());
        envDB.setDatabaseVersion(metaData.getDatabaseProductVersion());
        envDB.setDriverName(metaData.getDriverName());
        envDB.setDriverVersion(metaData.getDriverVersion());
        envDB.setUrl(metaData.getURL());
        envDB.setUsername(metaData.getUserName());
        envDB.setMaxConnections(metaData.getMaxConnections());
        //
        metaData.getConnection().close();
        //
        return envDB;
    } catch (SQLException e) {
        throw new UnsupportedOperationException(e);
    }
}