I want to fetch list of tables from mysql database from nodejs

Viewed 3746
connection.query('SHOW tables', function(err, tables){ 
    console.log(tables);
});

this query returns :

[
  RowDataPacket { Tables_in_books: 'au' },
  RowDataPacket { Tables_in_books: 'authors' },
  RowDataPacket { Tables_in_books: 'customers' },
  RowDataPacket { Tables_in_books: 'persons' },
  RowDataPacket { Tables_in_books: 'user' }
]

But i only want the names. i.e. output should be au, authors, cutomers, persons, user. basically i just need name of tables in string format.

3 Answers

MySQL has a built in database that includes meta data about your databases, this database name is information_schema.

So you can query it by doing something as follows

SELECT table_name FROM information_schema.tables WHERE table_schema ='Database Name';

so for you, you can do this

connection.query(`SELECT table_name FROM information_schema.tables WHERE table_schema = abc`, function(err, tables){ 
    console.log(tables);
});

You can learn more about information_schema here https://dev.mysql.com/doc/mysql-infoschema-excerpt/5.7/en/

select table_name from information_schema.tables

where table_schema - 'books'

Your problem is a javascript problem. All you needed to do was loop through the array being returned and add the value of each object to an array.

const result = tables.map(table => table['Table_in_books'])

I think this should solve your problem

Related