I was wondering how I could get the columns of a database table and store each of them in a string or string array. I have the following code but I believe it does not work.
Unless you've defined it, USER_TAB_COLUMN
is not a table or view in MySQL.
To get column names, query the information_schema.columns
view.
e.g.
to get a list of column names that in the foo.bar
table:
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'foo'
AND table_name = 'bar'
(Since the same table_name can appear in multiple databases, to ensure you will get the column names from a a single table, you'd need to specify the database the table is in. This also improves efficiency of the query, if you have lots of databases, because it limits the databases that MySQL needs to check.)
To check for columns of a table in the "current" database, you can make use of the DATABASE()
function:
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'bar'
(This would be the table referenced by SELECT * FROM bar
from the current database connection.)