Home > Blockchain >  INSERT table names using SELECT statement in MySQL
INSERT table names using SELECT statement in MySQL

Time:07-23

In MySQL, I know I can list the tables in a database with:

SHOW TABLES

But I want to insert a table name into a specified table, for example:

INSERT INTO dataset_names (dataset)
SELECT table_name FROM information_schema.tables
WHERE table_schema = '%s';

But when I execute the above statement, the dataset_names table does not get updated. I created the master table using:

CREATE TABLE dataset_names (id INT AUTO_INCREMENT PRIMARY KEY, dataset text);

Here is the python code.

    dataset_name_query = """
                        INSERT INTO dataset_names (dataset) values(
                        SELECT table_name FROM information_schema.tables
                        WHERE table_schema = '%s');
                        """% (tablename)
    
    csv_obj.read()
    csv_obj.create()
    cursor = createConnection()
    #Cursor executing the dataset insert into master table query
    cursor.execute(dataset_name_query)
    closeCursor(cursor)

CodePudding user response:

You should use a prepared statement, not string formatting. You also need to call connection.commit() to make the changes permanent; replace connection with the name of your connection variable (it's not shown in your example code).

dataset_name_query = """
    INSERT INTO dataset_names (dataset)
    SELECT table_name FROM information_schema.tables
    WHERE table_schema = %s;
    """

cursor = createConnection()
#Cursor executing the dataset insert into master table query
cursor.execute(dataset_name_query, [tablename])
connection.commit()
closeCursor(cursor)

CodePudding user response:

INSERT INTO table_names(name) (SELECT table_name FROM information_schema.tables WHERE table_schema='database_name')

Here the order on insert values and select values must match;

CodePudding user response:

You are use wrong syntax to insert data in a table, you forgot to use 'values' keyword before providing values. Your command should be something like this -

INSERT INTO dataset_names (dataset) values(
SELECT table_name FROM information_schema.tables
WHERE table_schema = '%s');

This should work.

  • Related