简体   繁体   中英

INSERT table names using SELECT statement in MySQL

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)

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)

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.

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

这里插入值和选择值的顺序必须匹配;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM