微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.sql.DatabaseMetaData的实例源码

项目:ProyectoPacientes    文件MetaDataRegressionTest.java   
/**
 * Tests fix for BUG#38367 - DatabaseMetaData dbMeta = this.conn.getMetaData();
 * this.rs = dbMeta.getProcedureColumns("test",null,"nullableParameterTest",null);
 * ...
 * Short columnNullable = new Short(this.rs.getShort(12));
 * assertTrue("Parameter " + columnName + " do not allow null arguments",* columnNullable.intValue() == java.sql.DatabaseMetaData.procedureNullable);
 * was failing for no good reason.
 * 
 * @throws Exception
 *             if the test fails.
 */

public void testBug38367() throws Exception {
    if (!versionMeetsMinimum(5,0)) {
        return;
    }

    try {
        createProcedure("sptestBug38367","(OUT nfact VARCHAR(100),IN ccuenta VARCHAR(100),\nOUT ffact VARCHAR(100),\nOUT fdoc VARCHAR(100))" + "\nBEGIN\nEND");

        DatabaseMetaData dbMeta = this.conn.getMetaData();
        this.rs = dbMeta.getProcedureColumns(this.conn.getCatalog(),"sptestBug38367",null);
        while (this.rs.next()) {
            String columnName = this.rs.getString(4);
            Short columnNullable = new Short(this.rs.getShort(12));
            assertTrue("Parameter " + columnName + " is not java.sql.DatabaseMetaData.procedureNullable.",columnNullable.intValue() == java.sql.DatabaseMetaData.procedureNullable);
        }
    } finally {
    }
}
项目:ProyectoPacientes    文件MetaDataRegressionTest.java   
/**
 * Tests fix for BUG#8803,'DATA_TYPE' column from
 * DBMD.getBestRowIdentifier() causes Arrayindexoutofboundsexception when
 * accessed (and in fact,didn't return any value).
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug8803() throws Exception {
    String tableName = "testBug8803";
    createTable(tableName,"(field1 INT NOT NULL PRIMARY KEY)");
    DatabaseMetaData Metadata = this.conn.getMetaData();
    try {
        this.rs = Metadata.getBestRowIdentifier(this.conn.getCatalog(),tableName,DatabaseMetaData.bestRowNotPseudo,true);

        assertTrue(this.rs.next());

        this.rs.getInt("DATA_TYPE"); // **** Fails here *****
    } finally {
        if (this.rs != null) {
            this.rs.close();

            this.rs = null;
        }
    }

}
项目:incubator-netbeans    文件SchemaTest.java   
public ResultSet getColumns(String catalog,String schemaPattern,String tableNamePattern,String columnNamePattern) {
    if (catalog == null) {
        if ("s1table1".equals(tableNamePattern)) {
            return JDBCStubUtil.columnsResultSet(
                    new String[] { "S1TABLE1_INTEGER_COL","S1TABLE1_VARCHAR_COL","S1TABLE1_FK_COL" },new String[] { "INTEGER","VARCAHR","INTEGER" },new int[] { Types.INTEGER,Types.VARCHAR,Types.INTEGER },new int[] { 0,20,0 },new int[] { DatabaseMetaData.columnNoNulls,DatabaseMetaData.columnNullable,DatabaseMetaData.columnNullable }
            );

        } else if ("s1table2".equals(tableNamePattern)) {
            return JDBCStubUtil.columnsResultSet(
                    new String[] { "S1TABLE2_INTEGER_COL" },new String[] { "INTEGER" },new int[] { Types.INTEGER },new int[] { 0 },new int[] { DatabaseMetaData.columnNoNulls }
            );
        }
    }
    return JDBCStubUtil.emptyResultSet();
}
项目:OpenVertretung    文件MetaDataRegressionTest.java   
public void testQuotedGunk() throws Exception {
    createTable("testQuotedGunk","(field1 int)");

    String quotedCatalog = "`" + this.conn.getCatalog() + "`";
    String unquotedCatalog = this.conn.getCatalog();

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getTables(quotedCatalog,"testQuotedGunk",new String[] { "TABLE" });
    assertTrue(this.rs.next());
    this.rs = dbmd.getTables(unquotedCatalog,new String[] { "TABLE" });
    assertTrue(this.rs.next());
    this.rs = dbmd.getColumns(quotedCatalog,"field1");
    assertTrue(this.rs.next());
    this.rs = dbmd.getColumns(unquotedCatalog,"field1");
    assertTrue(this.rs.next());

}
项目:the-vigilantes    文件MetadataTest.java   
/**
 * Tests the implementation of @R_993_4045@ion Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5,7)) {
        createTable("t1","(c1 char(1))");
        Properties props = new Properties();
        props.put("use@R_993_4045@ionSchema","true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData MetaData = conn1.getMetaData();
            this.rs = MetaData.getColumns(null,"t1",null);
            this.rs.next();
            assertEquals("t1",this.rs.getString("TABLE_NAME"));
            assertEquals("c1",this.rs.getString("COLUMN_NAME"));
            assertEquals("CHAR",this.rs.getString("TYPE_NAME"));
            assertEquals("1",this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
项目:ProyectoPacientes    文件MetaDataRegressionTest.java   
/**
 * Tests whether or not unsigned columns are reported correctly in
 * DBMD.getColumns
 * 
 * @throws Exception
 */
public void testGetColumnsUnsigned() throws Exception {
    try {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testGetUnsignedCols");
        this.stmt.executeUpdate("CREATE TABLE testGetUnsignedCols (field1 BIGINT,field2 BIGINT UNSIGNED)");

        DatabaseMetaData dbmd = this.conn.getMetaData();

        this.rs = dbmd.getColumns(this.conn.getCatalog(),"testGetUnsignedCols","%");

        assertTrue(this.rs.next());
        // This row doesn't have 'unsigned' attribute
        assertTrue(this.rs.next());
        assertTrue(this.rs.getString(6).toLowerCase().indexOf("unsigned") != -1);
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testGetUnsignedCols");
    }
}
项目:BibliotecaPS    文件MetaDataRegressionTest.java   
private void checkFunctionColumnTypeForBug68307(String testAgainst,DatabaseMetaData testDbMetaData) throws Exception {
    rs = testDbMetaData.getFunctionColumns(null,"testBug68307_%","%");

    while (rs.next()) {
        String message = testAgainst + ",function <" + rs.getString("FUNCTION_NAME") + "." + rs.getString("COLUMN_NAME") + ">";
        if (rs.getString("COLUMN_NAME") == null || rs.getString("COLUMN_NAME").length() == 0) {
            assertEquals(message,DatabaseMetaData.functionReturn,rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_in")) {
            assertEquals(message,DatabaseMetaData.functionColumnIn,rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_inout")) {
            assertEquals(message,DatabaseMetaData.functionColumnInOut,rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_out")) {
            assertEquals(message,DatabaseMetaData.functionColumnOut,rs.getShort("COLUMN_TYPE"));
        } else {
            fail("Column '" + rs.getString("FUNCTION_NAME") + "." + rs.getString("COLUMN_NAME") + "' not expected within test case.");
        }
    }
}
项目:kinetica-client-jdbc    文件JDBCSample.java   
/**
 * Retrieves a description of tables available for given connection.
 * 
 * @param conn
 *            The connection used to list the tables.
 * @throws sqlException
 *             if error happens while querying the data source.
 */
private static void showTables(Connection conn) throws sqlException {
    assert (conn != null);

    DatabaseMetaData Meta = conn.getMetaData();

    ResultSet result = null;
    try {
        result = Meta.getTables(null,null);
        printResultSet(result);
    } finally {
        if (result != null) {
            result.close();
        }
    }
}
项目:OpenVertretung    文件MetaDataRegressionTest.java   
/**
 * Bug #43714 - use@R_993_4045@ionSchema with DatabaseMetaData.getExportedKeys()
 * throws exception
 */
public void testBug43714() throws Exception {
    Connection c_IS = null;
    try {
        c_IS = getConnectionWithProps("use@R_993_4045@ionSchema=true");
        DatabaseMetaData dbmd = c_IS.getMetaData();
        this.rs = dbmd.getExportedKeys("x","y","z");
    } finally {
        try {
            if (c_IS != null) {
                c_IS.close();
            }
        } catch (sqlException ex) {
        }
    }
}
项目:BibliotecaPS    文件MetaDataRegressionTest.java   
/**
 * Tests fix for BUG#21215151 - DATABASEMetaDATA.GETCATALOGS() FAILS TO SORT RESULTS.
 * 
 * DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for '@R_993_4045@ion_schema' which
 * is always returned in the first position.
 * This test creates set of databases around the relative position of '@R_993_4045@ion_schema' and checks the ordering of the final ResultSet.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21215151() throws Exception {
    createDatabase("z_testBug21215151");
    createDatabase("j_testBug21215151");
    createDatabase("h_testBug21215151");
    createDatabase("i_testBug21215151");
    createDatabase("a_testBug21215151");

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getCatalogs();

    System.out.println("Catalogs:");
    System.out.println("--------------------------------------------------");
    while (this.rs.next()) {
        System.out.println("\t" + this.rs.getString(1));
    }
    this.rs.beforeFirst();

    // check the relative position of each element in the result set compared to the prevIoUs element.
    String prevIoUsDb = "";
    while (this.rs.next()) {
        assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the prevIoUs catalog. Check the system output to see the catalogs list.",prevIoUsDb.compareto(this.rs.getString(1)) < 0);
        prevIoUsDb = this.rs.getString(1);
    }
}
项目:gmds    文件Utils.java   
/**
     *
     * @param dbmdJson
     * @param repo
     * @param tree
     * @param conn
     * @param clmnTree
     * @return
     * @throws IOException
     * @throws sqlException
     */
    public static ObjectId MetaTreeCommit(ObjectJson dbmdJson,Repository repo,TreeFormatter tree,Connection conn,Boolean clmnTree) throws IOException,sqlException {

        DatabaseMetaData dbmd = conn.getMetaData();
//        ObjectJson dbmdJson = new ObjectJson();
        String mapString = MetaDbInfo(dbmd);
        ObjectInserter objectInserter = repo.newObjectInserter();
        ObjectId blobId = objectInserter.insert(Constants.OBJ_BLOB,mapString.getBytes());
        objectInserter.flush();

        tree.append(Consts.DATABASE,FileMode.REGULAR_FILE,blobId);
        Utils.putTableMeta(repo,conn,dbmd,objectInserter,tree,clmnTree);

        ObjectId treeId = objectInserter.insert(tree);
        objectInserter.flush();

        System.out.println("Tree ID: " + treeId.getName());

        return treeId;
    }
项目:syndesis    文件sqlIconFileStore.java   
private boolean tableExists(Handle h,String tableName) {
    try {
        String tabletocheck = tableName;
        boolean caseSensitive = this.databaseKind == DatabaseKind.Postgresql;
        if (!caseSensitive) {
            tabletocheck = tableName.toupperCase(Locale.ROOT);
        }
        DatabaseMetaData MetaData = h.getConnection().getMetaData();

        try (ResultSet rs = MetaData.getTables(null,tabletocheck,null)) {
            while (rs.next()) {
                String foundTable = rs.getString("TABLE_NAME");
                if (tabletocheck.equalsIgnoreCase(foundTable)) {
                    return true;
                }
            }
        }
        return false;
    } catch (sqlException ex) {
        throw IconDataAccessException.launderThrowable("Cannot check if the table " + tableName + " already exists",ex);
    }
}
项目:org.mybatis.generator.core-1.3.5    文件DatabaseIntrospector.java   
/**
 * Instantiates a new database introspector.
 *
 * @param context
 *            the context
 * @param databaseMetaData
 *            the database Meta data
 * @param javaTypeResolver
 *            the java type resolver
 * @param warnings
 *            the warnings
 */
public DatabaseIntrospector(Context context,DatabaseMetaData databaseMetaData,JavaTypeResolver javaTypeResolver,List<String> warnings) {
    super();
    this.context = context;
    this.databaseMetaData = databaseMetaData;
    this.javaTypeResolver = javaTypeResolver;
    this.warnings = warnings;
    logger = LogFactory.getLog(getClass());

    //获取数据库的版本信息
    try {
        DatabaseMetaData md = databaseMetaData.getConnection().getMetaData();
        databaseProductName = md.getDatabaseProductName().toupperCase();
    } catch (sqlException se) {
        warnings.add("获取数据库版本失败:" + se.getMessage());
    }
}
项目:OpenVertretung    文件MetadataTest.java   
/**
 * Tests the implementation of @R_993_4045@ion Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5,this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
项目:BibliotecaPS    文件MetadataTest.java   
/**
 * Tests the implementation of @R_993_4045@ion Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5,this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
项目:the-vigilantes    文件MetaDataRegressionTest.java   
/**
 * Tests fix for Bug#8812,DBMD.getIndexInfo() returning inverted values for
 * 'NON_UNIQUE' column.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug8812() throws Exception {
    String tableName = "testBug8812";

    try {
        createTable(tableName,"(field1 INT,field2 INT,INDEX(field1),UNIQUE INDEX(field2))");

        DatabaseMetaData dbmd = this.conn.getMetaData();
        this.rs = dbmd.getIndexInfo(this.conn.getCatalog(),true,false);
        assertTrue(this.rs.next()); // there should be one row that meets
        // this requirement
        assertEquals(this.rs.getBoolean("NON_UNIQUE"),false);

        this.rs = dbmd.getIndexInfo(this.conn.getCatalog(),false,false);
        assertTrue(this.rs.next()); // there should be two rows that meets
        // this requirement
        assertEquals(this.rs.getBoolean("NON_UNIQUE"),false);
        assertTrue(this.rs.next());
        assertEquals(this.rs.getBoolean("NON_UNIQUE"),true);

    } finally {
        dropTable(tableName);
    }
}
项目:incubator-netbeans    文件DBTestBase.java   
protected final boolean columnInAnyIndex(String tablename,String colname)
        throws Exception {
    tablename = fixIdentifier(tablename);
    colname = fixIdentifier(colname);
    DatabaseMetaData md = getConnection().getMetaData();
    ResultSet rs = md.getIndexInfo(null,getSchema(),tablename,false);

    // printResults(rs,"columnInIndex(" + viewname + "," + colname +
    //    "," + indexname + ")");

    while ( rs.next() ) {
        String ixColName = rs.getString(9);
        if ( ixColName.equals(colname) ) {
            return true;
        }
    }

    return false;        
}
项目:BibliotecaPS    文件PreparedStatement.java   
private void buildrewriteBatchedParams(String sql,MysqLConnection conn,DatabaseMetaData Metadata,String encoding,SingleByteCharsetConverter converter) throws sqlException {
    this.valuesClause = extractValuesClause(sql,conn.getMetaData().getIdentifierQuoteString());
    String odkuClause = this.isOnDuplicateKeyUpdate ? sql.substring(this.locationOfOnDuplicateKeyUpdate) : null;

    String headsql = null;

    if (this.isOnDuplicateKeyUpdate) {
        headsql = sql.substring(0,this.locationOfOnDuplicateKeyUpdate);
    } else {
        headsql = sql;
    }

    this.batchHead = new ParseInfo(headsql,Metadata,encoding,converter,false);
    this.batchValues = new ParseInfo("," + this.valuesClause,false);
    this.batchODKUClause = null;

    if (odkuClause != null && odkuClause.length() > 0) {
        this.batchODKUClause = new ParseInfo("," + this.valuesClause + " " + odkuClause,false);
    }
}
项目:lams    文件NativeJdbcExtractorAdapter.java   
/**
 * Check for a ConnectionProxy chain,then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool,to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws sqlException {
    if (con == null) {
        return null;
    }
    Connection targetCon = DataSourceUtils.getTargetConnection(con);
    Connection nativeCon = doGetNativeConnection(targetCon);
    if (nativeCon == targetCon) {
        // We haven't received a different Connection,so we'll assume that there's
        // some additional proxying going on. Let's check whether we get something
        // different back from the DatabaseMetaData.getConnection() call.
        DatabaseMetaData MetaData = targetCon.getMetaData();
        // The following check is only really there for mock Connections
        // which might not carry a DatabaseMetaData instance.
        if (MetaData != null) {
            Connection MetaCon = MetaData.getConnection();
            if (MetaCon != null && MetaCon != targetCon) {
                // We've received a different Connection there:
                // Let's retry the native extraction process with it.
                nativeCon = doGetNativeConnection(MetaCon);
            }
        }
    }
    return nativeCon;
}
项目:ChronoBike    文件sqlClauseSPSupport.java   
public sqlClauseSPParamsDesc getStoredProcedureParamsList(DbConnectionBase dbConnection,String csstoredProcName)
{
    sqlClauseSPParamsDesc spParamsDesc = new sqlClauseSPParamsDesc();

    try
    {
        DatabaseMetaData dmd = dbConnection.getDbConnection().getMetaData();
        if (csstoredProcName.indexOf(".") != -1) // suppress the user if exists in the procedure
            csstoredProcName = csstoredProcName.substring(csstoredProcName.indexOf(".") + 1); 
        ResultSet rsParams = dmd.getProcedureColumns(null,dbConnection.getEnvironmentPrefix(),csstoredProcName.replace("_","\\_"),"%");
        boolean b = true;
        while(rsParams.next() && b)
        {
            spParamsDesc.addAParam(rsParams);
        }
    }
    catch (sqlException e)
    {           
        return null;
    }

    return spParamsDesc;
}
项目:ProyectoPacientes    文件MetaDataRegressionTest.java   
public void testBug31187() throws Exception {
    createTable("testBug31187","(field1 int)");

    Connection nullCatConn = getConnectionWithProps("nullCatalogMeansCurrent=false");
    DatabaseMetaData dbmd = nullCatConn.getMetaData();
    ResultSet dbTblCols = dbmd.getColumns(null,"testBug31187","%");

    boolean found = false;

    while (dbTblCols.next()) {
        String catalog = dbTblCols.getString("TABLE_CAT");
        String table = dbTblCols.getString("TABLE_NAME");
        boolean useLowerCaseTableNames = dbmd.storesLowerCaseIdentifiers();

        if (catalog.equals(nullCatConn.getCatalog())
                && (((useLowerCaseTableNames && "testBug31187".equalsIgnoreCase(table)) || "testBug31187".equals(table)))) {
            found = true;
        }
    }

    assertTrue("Didn't find any columns for table named 'testBug31187' in database " + this.conn.getCatalog(),found);
}
项目:bdf2    文件EntityPR.java   
private String getColumnRemarks(String tableName,String columnName,DatabaseMetaData databaseMetaData) throws sqlException{
    String remarks=null;
    ResultSet rs=null;
    try{
        rs=databaseMetaData.getColumns(null,"%");
        while(rs.next()){
            String colName=rs.getString("COLUMN_NAME");
            if(columnName.equals(colName)){
                remarks=rs.getString("REMARKS");
                break;
            }
        }
    }finally{
        if(rs!=null)rs.close();
    }
    return remarks;
}
项目:ProyectoPacientes    文件MetaDataRegressionTest.java   
private void checkMetadataForBug22613(Connection c) throws Exception {
    String maxValue = "a,bc,def,ghij";
    String maxValue2 = "1,2,3,4,1585,ONE,TWO,Y,N,THREE";

    DatabaseMetaData Meta = c.getMetaData();
    this.rs = Meta.getColumns(null,this.conn.getCatalog(),"bug22613","s");
    this.rs.first();

    assertEquals(maxValue.length(),this.rs.getInt("COLUMN_SIZE"));

    this.rs = Meta.getColumns(null,"s2");
    this.rs.first();

    assertEquals(maxValue2.length(),c.getCatalog(),"t");
    this.rs.first();

    assertEquals(4,this.rs.getInt("COLUMN_SIZE"));
}
项目:calcite-avatica    文件MetaResultSetTest.java   
@Test public void testGetColumnPrivileges() throws sqlException {
  DatabaseMetaData Metadata = getDatabaseMetadata();
  try (ResultSet rs = Metadata.getColumnPrivileges(null,null)) {
    ResultSetMetaData rsMeta = rs.getMetaData();

    assertEquals(8,rsMeta.getColumnCount());
    assertColumn(rsMeta,1,"TABLE_CAT",DatabaseMetaData.columnNullable);
    assertColumn(rsMeta,"TABLE_SCHEM","TABLE_NAME",DatabaseMetaData.columnNoNulls);
    assertColumn(rsMeta,"COLUMN_NAME",5,"GRANTOR",6,"GRANTEE",7,"PRIVILEGE",8,"IS_GRANTABLE",DatabaseMetaData.columnNullable);
  }
}
项目:QDrill    文件Drill2489CallsAfterCloseThrowExceptionsTest.java   
@BeforeClass
public static void setUpConnection() throws Exception {
  // (Note: Can't use JdbcTest's connect(...) for this test class.)
  final Connection connection =
      new Driver().connect( "jdbc:drill:zk=local",JdbcAssert.getDefaultProperties() );
  final Statement stmt = connection.createStatement();
  final ResultSet result =
      stmt.executeQuery( "SELECT * FROM @R_993_4045@ION_SCHEMA.CATALOGS" );
  result.next();
  final DatabaseMetaData dbmd = connection.getMetaData();

  result.close();
  closedResultSet = result;
  stmt.close();
  closedStatement = stmt;
  connection.close();
  closedConnection = connection;
  closedDatabaseMetaData = dbmd;
}
项目:BibliotecaPS    文件MetaDataRegressionTest.java   
public void testBug44508() throws Exception {
    DatabaseMetaData dbmd = this.conn.getMetaData();

    this.rs = dbmd.getSuperTypes("","","");
    ResultSetMetaData rsmd = this.rs.getMetaData();

    assertEquals("TYPE_CAT",rsmd.getColumnName(1)); // Gives TABLE_CAT
    assertEquals("TYPE_SCHEM",rsmd.getColumnName(2)); // Gives TABLE_SCHEM
}
项目:OpenVertretung    文件MetadataTest.java   
/**
 * Tests the implementation of @R_993_4045@ion Schema for tables.
 */
public void testGetTablesUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5,7)) {
        createTable("`t1-1`","(c1 char(1))");
        createTable("`t1-2`","(c1 char(1))");
        createTable("`t2`","(c1 char(1))");
        Set<String> tableNames = new HashSet<String>();
        tableNames.add("t1-1");
        tableNames.add("t1-2");
        Properties props = new Properties();
        props.put("use@R_993_4045@ionSchema","true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData MetaData = conn1.getMetaData();
            // pattern matching for table name
            this.rs = MetaData.getTables(null,"t1-_",null);
            while (this.rs.next()) {
                assertTrue(tableNames.remove(this.rs.getString("TABLE_NAME")));
            }
            assertTrue(tableNames.isEmpty());
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
项目:BibliotecaPS    文件MetaDataRegressionTest.java   
/**
 * Test fix for BUG#68098 - DatabaseMetaData.getIndexInfo sorts results incorrectly.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug68098() throws Exception {
    String[] testStepDescription = new String[] { "MysqL MetaData","I__S MetaData" };
    Connection connUseIS = getConnectionWithProps("use@R_993_4045@ionSchema=true");
    Connection[] testConnections = new Connection[] { this.conn,connUseIS };
    String[] expectedindexesOrder = new String[] { "index_1","index_1","index_3","PRIMARY","index_2","index_4" };

    this.stmt.execute("DROP TABLE IF EXISTS testBug68098");

    createTable("testBug68098","(column_1 INT NOT NULL,column_2 INT NOT NULL,column_3 INT NOT NULL,PRIMARY KEY (column_1))");

    this.stmt.execute("CREATE INDEX index_4 ON testBug68098 (column_2)");
    this.stmt.execute("CREATE UNIQUE INDEX index_3 ON testBug68098 (column_3)");
    this.stmt.execute("CREATE INDEX index_2 ON testBug68098 (column_2,column_1)");
    this.stmt.execute("CREATE UNIQUE INDEX index_1 ON testBug68098 (column_3,column_2)");

    for (int i = 0; i < testStepDescription.length; i++) {
        DatabaseMetaData testDbMetaData = testConnections[i].getMetaData();
        this.rs = testDbMetaData.getIndexInfo(null,"testBug68098",false);
        int ind = 0;
        while (this.rs.next()) {
            assertEquals(testStepDescription[i] + ",sort order is wrong",expectedindexesOrder[ind++],this.rs.getString("INDEX_NAME"));
        }
        this.rs.close();
    }

    connUseIS.close();
}
项目:aries-jpa    文件DummyDataSource.java   
private Object proxyClasses(ClassLoader classLoader,Class<?> type) {
    if (type == DatabaseMetaData.class) {
        return createProxy(classLoader,DatabaseMetaData.class);
    }
    if (type == ResultSet.class) {
        return createProxy(classLoader,ResultSet.class);
    }
    if (type == Statement.class) {
        return createProxy(classLoader,PreparedStatement.class);
    }
    return null;
}
项目:syndesis    文件DatabaseMetaDataHelper.java   
static List<sqlParam> getJDBCInfoByColumnorder(final DatabaseMetaData Meta,String catalog,String schema,String tableName,final List<sqlParam> params) throws sqlException {
    List<sqlParam> paramList = new ArrayList<>();
    ResultSet columnSet = Meta.getColumns(catalog,"SA",null);
    for (int i=0; i<params.size(); i++) {
        columnSet.next();
        sqlParam param = params.get(i);
        param.setColumn(columnSet.getString("COLUMN_NAME"));
        param.setJdbcType(JDBCType.valueOf(columnSet.getInt("DATA_TYPE")));
        paramList.add(param);
    }
    return paramList;
}
项目:holon-datastore-jdbc    文件JdbcDatastoreUtils.java   
/**
 * Get the primary key {@link Path}s of given <code>table</code> using database Metadata,if available.
 * @param dialect Jdbc dialect
 * @param table Table name for which to obtain th primary key
 * @param connection Connection to use
 * @return The table primary key {@link Path}s,empty if not available
 * @throws sqlException Error accessing the database
 */
public static Optional<Path<?>[]> getPrimaryKey(JdbcDialect dialect,String table,Connection connection)
        throws sqlException {
    ObjectUtils.argumentNotNull(table,"Table name must be not null");
    ObjectUtils.argumentNotNull(connection,"Connection name must be not null");

    final String tableName = dialect.getTableName(table);

    List<Orderedpath> paths = new ArrayList<>();

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    try (ResultSet resultSet = databaseMetaData.getPrimaryKeys(null,tableName)) {
        while (resultSet.next()) {
            final String columnName = resultSet.getString("COLUMN_NAME");
            Orderedpath op = new Orderedpath();
            op.path = Path.of(columnName,getColumnType(databaseMetaData,columnName));
            op.sequence = resultSet.getShort("KEY_SEQ");
            paths.add(op);
        }
    }

    if (!paths.isEmpty()) {
        Collections.sort(paths);
        return Optional
                .of(paths.stream().map(p -> p.path).collect(Collectors.toList()).toArray(new Path[paths.size()]));
    }

    return Optional.empty();
}
项目:holon-datastore-jdbc    文件MysqLDialect.java   
@Override
public void init(JdbcDatastore datastore) throws sqlException {
    datastore.withConnection(c -> {
        DatabaseMetaData databaseMetaData = c.getMetaData();
        supportsGeneratedKeys = databaseMetaData.supportsGetGeneratedKeys();
        generatedKeyAlwaysReturned = databaseMetaData.generatedKeyAlwaysReturned();
        supportsLikeEscapeClause = databaseMetaData.supportsLikeEscapeClause();
        return null;
    });
}
项目:elastic-job-cloud    文件JobEventRdbStorage.java   
private void createJobExecutionTableAndindexIfNeeded(final Connection conn) throws sqlException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    try (ResultSet resultSet = dbMetaData.getTables(null,TABLE_JOB_EXECUTION_LOG,new String[]{"TABLE"})) {
        if (!resultSet.next()) {
            createJobExecutionTable(conn);
        }
    }
}
项目:incubator-netbeans    文件JDBCUtils.java   
public static Nullable getColumnNullable(int dbmdColumnNullable) {
    switch (dbmdColumnNullable) {
        case DatabaseMetaData.columnNoNulls:
            return Nullable.NOT_NULLABLE;
        case DatabaseMetaData.columnNullable:
            return Nullable.NULLABLE;
        case DatabaseMetaData.columnNullableunkNown:
        default:
            return Nullable.UNKNowN;
    }
}
项目:linkifier    文件Table.java   
public void getUniqueConstraint(DatabaseMetaData MetaData,String databaseName,String schemaName,String tableName) throws sqlException {
    try (ResultSet result = MetaData.getIndexInfo(databaseName,schemaName,true)) {
        while (result.next()) {
            for (Column col : columnList) {
                if (col.getName().equals(result.getString(9))) {
                    col.setUniqueConstraint(true);
                }
            }
        }
    }
}
项目:incubator-netbeans    文件OracleSchema.java   
@Override
protected void createTables() {
    LOGGER.log(Level.FINE,"Initializing tables in {0}",this);
    Map<String,Table> newTables = new LinkedHashMap<String,Table>();
    try {
        DatabaseMetaData dmd = jdbcCatalog.getJDBCMetadata().getDmd();
        Set<String> recycleBinTables = getRecycleBinObjects(dmd,"TABLE"); // NOI18N
        ResultSet rs = dmd.getTables(jdbcCatalog.getName(),name,"%",new String[]{"TABLE"}); // NOI18N
        if (rs != null) {
            try {
                while (rs.next()) {
                    String type = MetadataUtilities.trimmed(rs.getString("TABLE_TYPE")); //NOI18N
                    String tableName = rs.getString("TABLE_NAME"); // NOI18N
                    if (!recycleBinTables.contains(tableName)) {
                        Table table = createJDBCTable(tableName,type.contains("SYstem")).getTable(); //NOI18N
                        newTables.put(tableName,table);
                        LOGGER.log(Level.FINE,"Created table {0}",table);
                    } else {
                        LOGGER.log(Level.FINE,"Ignoring recycle bin table ''{0}''",tableName);
                    }
                }
            } finally {
                rs.close();
            }
        }
    } catch (sqlException e) {
        throw new MetadataException(e);
    }
    tables = Collections.unmodifiableMap(newTables);
}
项目:vertx-generator    文件DBUtil.java   
/**
 * 获得主键名称
 * 
 * @param config
 * @param tableName
 * @return
 * @throws Exception
 */
public static String getTablePrimaryKey(DatabaseConfig config,String tableName) throws Exception {
    Connection conn = getConnection(config);
    DatabaseMetaData md = conn.getMetaData();
    ResultSet rs = md.getPrimaryKeys(null,tableName);
    while (rs.next()) {
        return rs.getString("COLUMN_NAME");
    }
    return null;
}
项目:the-vigilantes    文件MetaDataRegressionTest.java   
public void testBug44508() throws Exception {
    DatabaseMetaData dbmd = this.conn.getMetaData();

    this.rs = dbmd.getSuperTypes("",rsmd.getColumnName(2)); // Gives TABLE_SCHEM
}
项目:the-vigilantes    文件MetaDataRegressionTest.java   
/**
 * Tests fix for BUG#68307 - getFunctionColumns() returns incorrect "COLUMN_TYPE" @R_993_4045@ion. This JDBC4
 * feature required some changes in method getProcedureColumns().
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug68307() throws Exception {
    String[] testStepDescription = new String[] { "MysqL MetaData",connUseIS };

    createFunction("testBug68307_func","(func_param_in INT) RETURNS INT DETERMINISTIC RETURN 1");

    createProcedure("testBug68307_proc","(IN proc_param_in INT,OUT proc_param_out INT,INOUT proc_param_inout INT) SELECT 1");

    for (int i = 0; i < testStepDescription.length; i++) {
        DatabaseMetaData testDbMetaData = testConnections[i].getMetaData();
        this.rs = testDbMetaData.getProcedureColumns(null,"%");

        while (this.rs.next()) {
            String message = testStepDescription[i] + ",procedure/function <" + this.rs.getString("PROCEDURE_NAME") + "."
                    + this.rs.getString("COLUMN_NAME") + ">";
            if (this.rs.getString("COLUMN_NAME") == null || this.rs.getString("COLUMN_NAME").length() == 0) {
                assertEquals(message,DatabaseMetaData.procedureColumnReturn,this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_in")) {
                assertEquals(message,DatabaseMetaData.procedureColumnIn,this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_inout")) {
                assertEquals(message,DatabaseMetaData.procedureColumnInOut,this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_out")) {
                assertEquals(message,DatabaseMetaData.procedureColumnOut,this.rs.getShort("COLUMN_TYPE"));
            } else {
                fail(testStepDescription[i] + ",column '" + this.rs.getString("FUNCTION_NAME") + "." + this.rs.getString("COLUMN_NAME")
                        + "' not expected within test case.");
            }
        }

        this.rs.close();
    }
}
项目:the-vigilantes    文件MetaDataRegressionTest.java   
private void checkMetaDataInfoForBug17248345(Connection testConn) throws Exception {
    DatabaseMetaData testDbMetaData = testConn.getMetaData();
    ResultSet rsMD;
    boolean useInfoSchema = ((ConnectionProperties) testConn).getUse@R_993_4045@ionSchema();
    boolean getProcRetFunc = ((ConnectionProperties) testConn).getGetProceduresReturnsFunctions();
    String stepDescription = "Prop. useInfoSchema(" + (useInfoSchema ? 1 : 0) + ") + getProcRetFunc(" + (getProcRetFunc ? 1 : 0) + "):";
    String sd;

    // getProcedures() must return 2 records,even if getProceduresReturnsFunctions is false once this flag only
    // applies to JDBC4. When exists a procedure and a function with same name,function is returned first.
    sd = stepDescription + " getProcedures() ";
    rsMD = testDbMetaData.getProcedures(null,"testBug17248345");
    assertTrue(sd + "1st of 2 rows expected.",rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME","testBug17248345",rsMD.getString("PROCEDURE_NAME"));
    assertTrue(sd + "2nd of 2 rows expected.",rsMD.getString("PROCEDURE_NAME"));
    assertFalse(sd + "no more rows expected.",rsMD.next());

    // getProcedureColumns() must return 3 records,even if getProceduresReturnsFunctions is false once this flag
    // only applies to JDBC4. When exists a procedure and a function with same name,function is returned first.
    sd = stepDescription + " getProcedureColumns() ";
    rsMD = testDbMetaData.getProcedureColumns(null,"%");
    assertTrue(sd + "1st of 3 rows expected.",rsMD.getString("PROCEDURE_NAME"));
    assertEquals(sd + " -> COLUMN_NAME",rsMD.getString("COLUMN_NAME"));
    assertTrue(sd + "2nd of 3 rows expected.","funccol",rsMD.getString("COLUMN_NAME"));
    assertTrue(sd + "3rd of 3 rows expected.","proccol",rsMD.getString("COLUMN_NAME"));
    assertFalse(sd + "no more rows expected.",rsMD.next());
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。