How can I get all tables names of a schema? I have tried this:
DatabaseMetaData metaData = (DatabaseMetaData) conn.getMetaData();
metaData.getTables(null, schema, null, null);
but it does not work.
Finally I have made this:
conn.setCatalog(mySchema);
String sqlQuery = "show tables";
rs = ps.executeQuery(sqlQuery);
while (rs.next())
{
System.out.print(rs.getString(1));
}
ResultSet tables = metaData.getTables(null, null, null, new String[] {"TABLE"});
while (tables.next()){
System.out.print(tables.getString("TABLE_NAME") + " ");
}
EDIT: Second parameter is where you specify the schema pattern (e.g. "Sales"), null for all schemas.
Try the following:
DatabaseMetaData metaData = (DatabaseMetaData) conn.getMetaData();
ResultSet rs = metaData.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
The documentation says that the third column is TABLE_NAME.
For mysql:5.6 -
To get particular tables of a particular schema, I have to pass the schema name as "catalog" parameter(1st param). It was ignoring, if I pass it as "schemaPattern" parameter( 2nd param).
I assumed that it has to do with the fact that "create schema' is a synonym for "create database" in mysql.
https://dev.mysql.com/doc/refman/8.0/en/create-database.html
DatabaseMetaData meta = (DatabaseMetaData)
support.getConnection().getMetaData();
rs = meta.getTables("schema_name", null, null, new String[] { "TABLE" });
while (rs.next()) {
String tblName = rs.getString("TABLE_NAME");
System.out.println(tblName);
}
Related
I am Retrieving some tables from database and storing those table names in a hashset. Code I am using to retrieve table is as follows
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
Now I have tables in a hash set.
Now I want to retrieve data from all these tables in a hash set for particular column 'student'. And put all values in a list. I want to retrieve all distinct values of column student in all these tables. Table may contain or may not contain this student column. If a table contains this column then I want to store its distinct values in a list. Please suggest how to do it.
Note that you can not extract table data using the databasemetadata. Databasemetadata will only provide you the details of table like name, columns, datatypes etc. You need to make the JDBC connection with the database and then need to fire the select query to get the desired result.
Below is the simple JDBC program to do so:
DatabaseMetaData md = conn.getMetaData();
// get tables from database
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
// getColumns of table 'tableName'
ResultSet rs2 = md.getColumns(null, null, tableName, null);
boolean found = false;
while (rs2.next()) {
String columnName = rs2.getString("COLUMN_NAME");
if (columnName.equalsIgnoreCase("student")) {
found = true;
break;
}
}
if (found) {
String driver = "provide the driver for database here like com.mysql.....";
String url = "provide the connection url here like jdbc://...."
String userName = "provide DB username"
String password = "provide DB username"
Class.forName(driver)
Connection conn = DriverManager.getConnection(url, userName, password)
Statement st = conn.createStatement();
Resultset rs3 = null;
// Now take the tableName from your hashset and pass it into below query.
String query = "select student from " + tableName;
rs3 = st.executeQuery(query);
While(rs3.next()) {
// Store the results anywhere you want by obtaining 'rs3.getString(1)'
}
}
Hope this resolves your problem. Please ignore typos in code if any.
I am able to create a java.sql.Connection object and get table data:
DatabaseMetaData metaData = connection.getMetaData();
String [] tableTypes = {"Table"};
ResultSet rs = metaData.getTables(null, null, null, tableTypes);
if (rs != null) {
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
// Do some further table analysis
}
}
How do I get the Queries saved in the mdb file as well? (specifically, their names, and the SQL statements that they are made of)
Thanks!
Use Jackcess:
Database db = DatabaseBuilder.open(new File("access.mdb"));
for (Query query : db.getQueries()) {
System.out.println(query.getName() + ": " + query.toSQLString());
}
Trying to understand what is going on here. DatabaseMetaData is returning an empty result set, where as an SQL query that is effectively the same does not. Not a major issue as I am using the second code example as a work around.
DatabaseMetaData dmd = this.connection.getMetaData();
ResultSet rs = dmd.getSchemas();
while (rs.next()){
// empty result set
}
Expected a non-empty result set.
ResultSet rs = this.connection.prepareStatement("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA;").executeQuery();
while (rs.next()){
// non-empty result set with expected results
}
Expected a non-empty result set and got it.
As far as I can tell the MySQL JDBC driver considers that a catalog, not a schema. So you should use getCatalogs instead (and everywhere you use it, you need to use the catalog parameter, not the schema parameter).
The getSchemas method in Connector/J always returns an empty result set:
public java.sql.ResultSet getSchemas() throws SQLException {
Field[] fields = new Field[2];
fields[0] = new Field("", "TABLE_SCHEM", java.sql.Types.CHAR, 0);
fields[1] = new Field("", "TABLE_CATALOG", java.sql.Types.CHAR, 0);
ArrayList<ResultSetRow> tuples = new ArrayList<ResultSetRow>();
java.sql.ResultSet results = buildResultSet(fields, tuples);
return results;
}
The getCatalogs returns the result of SHOW DATABASES. And in DatabaseMetaDataUsingInfoSchema you see the TABLE_SCHEMA column of the information schema aliased as TABLE_CAT (for catalog) and the catalog parameter being passed as a value for the TABLE_SCHEMA column in the query:
String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME,"
+ "COLUMN_NAME, NULL AS GRANTOR, GRANTEE, PRIVILEGE_TYPE AS PRIVILEGE, IS_GRANTABLE FROM INFORMATION_SCHEMA.COLUMN_PRIVILEGES WHERE "
+ "TABLE_SCHEMA LIKE ? AND TABLE_NAME =? AND COLUMN_NAME LIKE ? ORDER BY COLUMN_NAME, PRIVILEGE_TYPE";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
pStmt.setString(3, columnNamePattern);
I realize this is an old post, but it comes up in a Google search on this topic, and the answer here did not work for me.
After much more digging, I found the correct way to do this.
First, you can get a list of all the metadata table types by doing this
DatabaseMetaData metaData = connection.getMetaData();
ResultSet rs = metaData.getTableTypes();
while (rs.next()) {
System.out.println(rs.getString(1));
}
The table type that we are interested in is simply called TABLE.
And this code will pull up all the names of the schema's in the SQL server, assuming your credentials have the rights to view them.
DatabaseMetaData metaData = connection.getMetaData();
ResultSet rs = metaData.getTables(null, null, null, new String[]{"TABLE"});
while(rs.next())
{
System.out.println(rs.getString(1));
}
It worked for me anyways with Java 8 and mysql-connector-java-8.0.22
I have the code as follows:
DatabaseMetaData dmd = connection.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
while(rs.next()){
primaryKey = rs.getString("COLUMN_NAME");
}
rs is not null while rs.next() always return false, anyone has idea about it? Thanks.
metadata interface implementation was implemented by driver vendors. It may not be supported by some driver and some db.
Here is text from javadoc:
Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet objects. If a given form of metadata is not available, an empty ResultSet will be returned.
table name is case sensitive in oracle
or try the below approach
DatabaseMetaData dm = conn.getMetaData( );
ResultSet rs = dm.getExportedKeys( "" , "" , "table1" );
while( rs.next( ) )
{
String pkey = rs.getString("PKCOLUMN_NAME");
System.out.println("primary key = " + pkey);
}
you can also use getCrossReference or getImportedKeys to retrieve primary key
I have csv file and i want to import that data to oracle database.
but before that i want it to check whether table 'xyz' exist in database or not.
I want to do it through java .. anyone knows how to do it through java ?
You can use the available meta data:
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, null,
new String[] {"TABLE"});
while (res.next()) {
System.out.println(
" "+res.getString("TABLE_CAT")
+ ", "+res.getString("TABLE_SCHEM")
+ ", "+res.getString("TABLE_NAME")
+ ", "+res.getString("TABLE_TYPE")
+ ", "+res.getString("REMARKS"));
}
See here for more details.
Wikipedia has some good info on getting at oracle metadata.
SELECT
COUNT(1)
FROM
ALL_TABLES
WHERE
TABLE_NAME = 'NAME_OF_TABLE'
Replace NAME_OF_TABLE with the name of your table and if you get a result of 1, you have your table.
You can just run a dummy SQL like:
select from * 'xyz' where 1 = 2
If you don't get any Exception like "ORA-00942 Table or View doesnt exist" then the Table exists.
Or you choose the elegant way like:
select * from USER_OBJECTS where OBJECT_TYPE = 'TABLE' and OBJECT_NAME = 'xyz';
public class Main
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#//server.local:1521/prod", "scott", "tiger");
conn.setAutoCommit(false);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rset = dbmd.getTables("", "SCOTT", "EMP", null);
while (rs.next())
{
System.out.println(rs.getString(3));
//OR use whatever progmatically you want to do if table exist
}
stmt.close();
}
}