I want to fetch all the tables and their columns metadata present in the database in json format.
in the json file, the tablename key value pair is showing only the last table in the database and not all.
My code is below:
ResultSet tables = databaseMetaData.getTables(catalog, schemaPattern, tableNamePattern, types);
while (tables.next()) {
String tableName = tables.getString(3);
jsonObject.put("tablename", tablename);
ResultSet columnMetadata = databaseMetaData.getColumns(null, null, tableName, null);
while (columnMetadata.next()) {
JSONObject record = new JSONObject();
record.put("Field_Name", columnMetadata.getString("COLUMN_NAME"));
record.put("Field_Length", columnMetadata.getString("COLUMN_SIZE"));
array.put(record);
}
jsonObject.put("field", array);
}
Any help would be appreciated.
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 doing a metadata fetch from teradata using jdbc and I would like to get all the datatypes. However for DB fields containing DECIMAL(10,4) I am not able to get the precision. I am attaching my code snippet. Suggestions would be welcome!
DatabaseMetaData md = con.getMetaData();
ResultSet tbls = md.getTables(null, schema, name, null);
if(false == tbls.next()){
nonExistingRdbmsTables.add(name);
LOGGER.error("Table with name {} in schema {} does not exists in source database", name, schema);
continue;
}
RdbmsTableMetadata tableMD = new RdbmsTableMetadata();
List<String> pkList = new ArrayList();
ResultSet primaryKeys = md.getPrimaryKeys(null, schema, name);
while(primaryKeys.next()){
String pk = primaryKeys.getString("COLUMN_NAME");
pkList.add(pk);
}
tableMD.setPkList(pkList);
LOGGER.info("*****Primary key list for table {} is {}", name, pkList);
tableMD.setSchema(schema);
tableMD.setName(name);
tableMD.setTargetName(targetName);
tableMD.setTargetSchema(targetSchema);
List<Column> colList = new ArrayList<>();
ResultSet cols = md.getColumns(null, schema, name, null);
while (cols.next()) {
String columnName = cols.getString("COLUMN_NAME");
String columnType = cols.getString("TYPE_NAME");
String columnLength = cols.getString("COLUMN_SIZE");
}
Is there any way I can query the precision details from jdbc metadata?
For future referencers:-
int precision = cols.getInt("DECIMAL_DIGITS");
This worked fine! Thanks to alex and Mark.
ResultSetMetaData provides getScale(int col) and getPrecision(int col) methods. If those don't give you what you want, you're probably out of luck.
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());
}
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);
}
The SQL DB has 110 tables and each table is having different column names. I have to loop through each table and fetch the data, so that I can write into a XML file.
For this, I created a new table called "MasterList" which holds all the 110 table names.
try{
// Connection for SQL Server.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://"+strDBServer+":1433;DatabaseName="
+ strDBName + ";" +
"User="+strDBUser+";Password="+strDBPassword+";";
Connection conn = DriverManager.getConnection(url);
if (conn != null) {
System.out.println("Connection Successful!");
}
//XML Transform
TransformerFactory tFactory = TransformerFactory.newInstance();
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Get List of all the tables present from Master table.
ResultSet rs = sql_stmt.executeQuery("SELECT TableName, Order FROM "
+ strDBName + ".[dbo].Master");
while (rs.next())
{
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
String strTableName=rs.getString(1).trim();
int intOrder = rs.getInt(2);
hsMapTablesFromDB.put(strTableName,intOrder);
System.out.println("Hashmap --> " + hsMapTablesFromDB);
ResultSet rs_1 = sql_stmt_1.executeQuery("SELECT Name, LevelOfExistence, UniqueId FROM "
+ strDBName + ".[dbo]." + strTableName);
String strName = rs_1.getString(1).trim();
String strUnique = rs_1.getString(3).trim();
hsMapDataFromIndTable.put(strName,strUnique);
System.out.println("hsMapDataFromIndTable" + hsMapDataFromIndTable);
}
}
catch(Exception e){
e.printStackTrace();
}
As the column names in each table will be different, how to get the corresponding column names in "sql_stmt_1.executeQuery", so that once I get each record from the table, I have to insert it.
Like wise all the 110 tables data has to be inserted into XML file.
Please help me.
Thanks
Ramm
Try using following query for your column names in each table
select column_name from information_schema.columns
where table_name = 'YourTableName' //this will your iterated loop table name.
Using this query you will get all column names from your table add those column name in next query of that table.
then update the XML.