當前位置: 首頁>>代碼示例>>Java>>正文


Java DatabaseMetaData.getPrimaryKeys方法代碼示例

本文整理匯總了Java中java.sql.DatabaseMetaData.getPrimaryKeys方法的典型用法代碼示例。如果您正苦於以下問題:Java DatabaseMetaData.getPrimaryKeys方法的具體用法?Java DatabaseMetaData.getPrimaryKeys怎麽用?Java DatabaseMetaData.getPrimaryKeys使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.sql.DatabaseMetaData的用法示例。


在下文中一共展示了DatabaseMetaData.getPrimaryKeys方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: columnInPrimaryKey

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
protected final boolean columnInPrimaryKey(String tablename, String colname)
    throws Exception {
    tablename = fixIdentifier(tablename);
    colname = fixIdentifier(colname);
    DatabaseMetaData md = getConnection().getMetaData();
    ResultSet rs = md.getPrimaryKeys(null, getSchema(), tablename);
    
    // printResults(rs, "columnInPrimaryKey(" + viewname + ", " +
    //        colname + ")");
            
    while ( rs.next() ) {
        String pkCol = rs.getString(4);
        if ( pkCol.equals(colname)) {
            return true;
        }
    }
    
    return false;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:20,代碼來源:DBTestBase.java

示例2: testGetPrimaryKeysUsingInfoShcema

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
/**
 * Tests the implementation of Information Schema for primary keys.
 */
public void testGetPrimaryKeysUsingInfoShcema() throws Exception {
    if (versionMeetsMinimum(5, 0, 7)) {
        createTable("t1", "(c1 int(1) primary key)");
        Properties props = new Properties();
        props.put("useInformationSchema", "true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData metaData = conn1.getMetaData();
            this.rs = metaData.getPrimaryKeys(null, null, "t1");
            this.rs.next();
            assertEquals("t1", this.rs.getString("TABLE_NAME"));
            assertEquals("c1", this.rs.getString("COLUMN_NAME"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
 
開發者ID:rafallis,項目名稱:BibliotecaPS,代碼行數:24,代碼來源:MetadataTest.java

示例3: findTablePrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
public List<String> findTablePrimaryKeys(String dataSourceName, String tableName) throws Exception {
	List<String> primaryKeys = new ArrayList<String>();
	Connection conn = null;
	ResultSet rs = null;
	try {
		conn = connectionHelper.getConnection(dataSourceName);
		DatabaseMetaData metaData = conn.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeys.add(rs.getString("COLUMN_NAME").toLowerCase());
		}
		return primaryKeys;
	} finally {
		if (conn != null) {
			conn.close();
		}
		if (rs != null) {
			rs.close();
		}
	}
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:22,代碼來源:ExcelModelManager.java

示例4: findTablePrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
public List<String> findTablePrimaryKeys(String dbInfoId, String tableName) throws Exception {
	List<String> primaryKeys = new ArrayList<String>();
	Connection con = null;
	ResultSet rs = null;
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	try {
		con = ds.getConnection();
		DatabaseMetaData metaData = con.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeys.add(rs.getString("COLUMN_NAME").toUpperCase());
		}
		return primaryKeys;
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(con);
	}
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:19,代碼來源:DbCommonServiceImpl.java

示例5: loadTablePrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
private List<String> loadTablePrimaryKeys(String tableName)throws Exception{
	DataSource ds=this.getJdbcTemplate().getDataSource();
	Connection con = DataSourceUtils.getConnection(ds);
	List<String> primaryKeyList=new ArrayList<String>();
	Statement stmt = null;
	ResultSet rs=null;
	try{
		DatabaseMetaData metaData = con.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeyList.add(rs.getString("COLUMN_NAME"));
		}
	}finally{
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		JdbcUtils.closeConnection(con);
	}
	return primaryKeyList;
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:20,代碼來源:EntityPR.java

示例6: loadTablePrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
private String loadTablePrimaryKeys(String tableName,DatabaseMetaData metaData) throws Exception{
	String keys="";
	ResultSet rs = null;
	try {
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		int i=0;
		while (rs.next()) {
			if(i>0){
				keys+=",";
			}
			i++;
			keys+=rs.getString("COLUMN_NAME");
		}
	} finally {
		JdbcUtils.closeResultSet(rs);
	}
	return keys;
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:19,代碼來源:QueryWizardPR.java

示例7: getTablePrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
public static List<Map<Integer, Object>> getTablePrimaryKeys(Connection conn, String tableSchema, String tableName) throws Exception {
	List<Map<Integer, Object>> primaryKeys = new ArrayList<Map<Integer, Object>>();
	Map<Integer, Object> primaryKey;
	DatabaseMetaData databaseMetaData = conn.getMetaData();
	if (tableSchema == null) {
		tableSchema = getDefaultTableSchema(conn);
	}
	ResultSet rs = null;
	try {
		rs = databaseMetaData.getPrimaryKeys(null, tableSchema, tableName.toUpperCase());
		while (rs.next()) {
			primaryKey = new HashMap<Integer, Object>();
			int i = 1;
			while (i <= 6) {
				primaryKey.put(i, rs.getObject(i));
				i++;
			}
			primaryKeys.add(primaryKey);
		}
		return primaryKeys;
	} finally {
		DbJdbcUtils.closeResultSet(rs);
	}
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:25,代碼來源:DbJdbcUtils.java

示例8: testGetPrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
public void testGetPrimaryKeys() throws SQLException {
    try {
        createTable("multikey", "(d INT NOT NULL, b INT NOT NULL, a INT NOT NULL, c INT NOT NULL, PRIMARY KEY (d, b, a, c))");
        DatabaseMetaData dbmd = this.conn.getMetaData();
        this.rs = dbmd.getPrimaryKeys(this.conn.getCatalog(), "", "multikey");

        short[] keySeqs = new short[4];
        String[] columnNames = new String[4];
        int i = 0;

        while (this.rs.next()) {
            this.rs.getString("TABLE_NAME");
            columnNames[i] = this.rs.getString("COLUMN_NAME");

            this.rs.getString("PK_NAME");
            keySeqs[i] = this.rs.getShort("KEY_SEQ");
            i++;
        }

        if ((keySeqs[0] != 3) && (keySeqs[1] != 2) && (keySeqs[2] != 4) && (keySeqs[3] != 1)) {
            fail("Keys returned in wrong order");
        }
    } finally {
        if (this.rs != null) {
            try {
                this.rs.close();
            } catch (SQLException sqlEx) {
                /* ignore */
            }
        }
    }
}
 
開發者ID:rafallis,項目名稱:BibliotecaPS,代碼行數:33,代碼來源:MetadataTest.java

示例9: getPrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
/**
 * Call {@link DatabaseMetaData#getPrimaryKeys(String, String, String)},
 * wrapping any internal runtime exeption into an {@link SQLException}.
 */
public static ResultSet getPrimaryKeys(DatabaseMetaData dmd,
        String catalog, String schema, String table) throws SQLException {
    try {
        return dmd.getPrimaryKeys(catalog, schema, table);
    } catch (SQLException e) {
        throw e;
    } catch (Throwable t) {
        throw new SQLException(t);
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:15,代碼來源:MetadataUtilities.java

示例10: getPrimaryKeyName

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
private String getPrimaryKeyName(String tableName) throws SQLException {
    DatabaseMetaData meta = this.databaseHandler.getConnection().getMetaData();
    ResultSet primaryKeys = meta.getPrimaryKeys((String)null, (String)null, tableName);
    String primaryKeyName = null;
    if(primaryKeys.next()) {
        primaryKeyName = primaryKeys.getString(4);
    }

    primaryKeys.close();
    return primaryKeyName;
}
 
開發者ID:transwarpio,項目名稱:rapidminer,代碼行數:12,代碼來源:IndexCachedDatabaseExampleTable.java

示例11: testTwo

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
/**
 * Basic test of DatabaseMetaData functions that access system tables
 */
public void testTwo() throws Exception {

    Connection conn = newConnection();
    int        updateCount;

    try {
        TestUtil.testScript(conn, "testrun/hsqldb/TestSelf.txt");

        DatabaseMetaData dbmeta = conn.getMetaData();

        dbmeta.allProceduresAreCallable();
        dbmeta.getBestRowIdentifier(null, null, "T_1",
                                    DatabaseMetaData.bestRowTransaction,
                                    true);
        dbmeta.getCatalogs();
        dbmeta.getColumnPrivileges(null, "PUBLIC", "T_1", "%");
        dbmeta.getColumns("PUBLIC", "PUBLIC", "T_1", "%");
        dbmeta.getCrossReference(null, null, "T_1", null, null, "T_1");
        dbmeta.getExportedKeys(null, null, "T_1");
        dbmeta.getFunctionColumns(null, "%", "%", "%");
        dbmeta.getFunctions(null, "%", "%");
        dbmeta.getImportedKeys("PUBLIC", "PUBLIC", "T_1");
        dbmeta.getIndexInfo("PUBLIC", "PUBLIC", "T1", true, true);
        dbmeta.getPrimaryKeys("PUBLIC", "PUBLIC", "T_1");
        dbmeta.getProcedureColumns(null, null, "%", "%");
        dbmeta.getProcedures("PUBLIC", "%", "%");
        dbmeta.getSchemas(null, "#");
        dbmeta.getTablePrivileges(null, "%", "%");
        dbmeta.getUDTs(null, "%", "%", new int[]{ Types.DISTINCT });
    } catch (Exception e) {
        assertTrue("unable to prepare or execute DDL", false);
    } finally {
        conn.close();
    }
}
 
開發者ID:tiweGH,項目名稱:OpenDiabetes,代碼行數:39,代碼來源:TestDatabaseMetaData.java

示例12: getPrimaryKey

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
@Override
public String getPrimaryKey(String tableName) {
  try {
    DatabaseMetaData metaData = this.getConnection().getMetaData();
    ResultSet results = metaData.getPrimaryKeys(null, null, tableName);
    if (null == results) {
      return null;
    }

    try {
      if (results.next()) {
        return results.getString("COLUMN_NAME");
      } else {
        return null;
      }
    } finally {
      results.close();
      getConnection().commit();
    }
  } catch (SQLException sqlException) {
    LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
        + sqlException.toString(), sqlException);
    return null;
  } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
}
 
開發者ID:BriData,項目名稱:DBus,代碼行數:30,代碼來源:SqlManager.java

示例13: exctractPrimaryKeyColumn

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
private String exctractPrimaryKeyColumn( String tableName, DatabaseMetaData databaseMetaData, String schemaPattern )
                                                                                                                     throws SQLException {

    ResultSet pkResultSet = databaseMetaData.getPrimaryKeys(null, schemaPattern, tableName);
    while (pkResultSet.next()) {
        // return the primary key column
        return pkResultSet.getString(4);
    }

    // no primary key for this table
    return null;
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:13,代碼來源:AbstractDbProvider.java

示例14: getPrimaryKeys

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
/**
 * Finds the primary keys for the {@code tableName}.
 *
 * @param tableName the table to query for.
 * @return a collection of the primary keys.
 */
protected List<String> getPrimaryKeys(String tableName) {
  List<PrimaryKeyColumn> columns = newArrayList();
  try {
    final DatabaseMetaData databaseMetaData = connection.getMetaData();

    ResultSet primaryKeyResults = databaseMetaData.getPrimaryKeys(null, schemaName, tableName);

    try {
      while (primaryKeyResults.next()) {
        columns.add(new PrimaryKeyColumn(primaryKeyResults.getShort(5), primaryKeyResults.getString(4)));
      }
    } finally {
      primaryKeyResults.close();
    }
  } catch (SQLException sqle) {
    throw new RuntimeSqlException("Error reading primary keys for table [" + tableName + "]", sqle);
  }

  List<PrimaryKeyColumn> sortedColumns = Ordering.from(new Comparator<PrimaryKeyColumn>() {
    @Override
    public int compare(PrimaryKeyColumn o1, PrimaryKeyColumn o2) {
      return o1.sequence.compareTo(o2.sequence);
    }
  }).sortedCopy(columns);

  // Convert to String before returning
  return transform(sortedColumns, new Function<PrimaryKeyColumn, String>() {
    @Override
    public String apply(PrimaryKeyColumn input) {
      return input.name;
    }
  });
}
 
開發者ID:alfasoftware,項目名稱:morf,代碼行數:40,代碼來源:DatabaseMetaDataProvider.java

示例15: getTables

import java.sql.DatabaseMetaData; //導入方法依賴的package包/類
/**
 * Gets tables.
 *
 * @param connection the connection
 * @param keys keys
 * @param tablesOverride the tables override @return the tables
 * @throws SQLException the sql exception
 */
public Map<String, Map<String, Object>> getTables(Connection connection, String keys,
                                                  Map<String, Map<String, Object>> tablesOverride) throws SQLException {
    Map<String, Map<String, Object>> dataMap = new HashMap<>(16);
    DatabaseMetaData metaData = connection.getMetaData();
    // 處理key列表
    List<String> keyList = new ArrayList<>(1);
    if (keys != null) {
        String[] keyArray = keys.split(",");
        keyList = Arrays.asList(keyArray);
    } else {
        keyList.add("%");
    }
    // 根據key列表抽取指定表
    for (String key : keyList) {
        ResultSet resultSet = metaData.getTables(null, null, key, null);
        while (resultSet.next()) {
            Map<String, Object> table = new HashMap<>(4);
            String tableName = resultSet.getString(TABLE_NAME);
            LOGGER.info("抽取表結構>>{}", tableName);
            // 獲取主鍵
            ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
            if (primaryKeys.next()) {
                String primaryColumn = primaryKeys.getString(COLUMN_NAME);
                table.put("primaryColumn", primaryColumn);
                table.put("primaryName", StringUtils.getCamelCaseString(primaryColumn, false));
                table.put("primaryAuto", false);
            } else {
                LOGGER.warn("獲取表{}主鍵失敗,跳過該表", tableName);
                continue;
            }
            table.put("tableName", tableName);
            table.put("comment", resultSet.getString(REMARKS));
            String className = StringUtils.getCamelCaseString(tableName, true);
            table.put("className", className);

            table.put("imports", new HashSet<>(5));

            // 使用配置文件進行覆蓋
            Map<String, Object> tableOverride = tablesOverride.get(tableName);
            Map<String, Map<String, Object>> columnsOverride = new HashMap<>(0);
            if (tableOverride != null) {
                table.putAll(tableOverride);
                table.remove("columns");
                List<Map<String, Object>> columnsOverrideList = (List<Map<String, Object>>) tableOverride.get("columns");
                if (columnsOverrideList != null) {
                    columnsOverride = columnsOverrideList.stream().collect(Collectors.toMap(o -> (String) o.get("columnName"),
                                                                                            o -> o));
                }
            }
            List<Map<String, Object>> columns = getColumns(connection, table, columnsOverride);
            table.put("columns", columns);
            dataMap.put(tableName, table);
        }
    }
    return dataMap;
}
 
開發者ID:sgota,項目名稱:tkcg,代碼行數:65,代碼來源:DbDataMapHelper.java


注:本文中的java.sql.DatabaseMetaData.getPrimaryKeys方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。