How can I run an sql command on all databases at once? - mysql

I have circa 80 wordpress blogs, which write about my various sites. I want to update all posts in all databases for a specific string of text, in this instance, a domain name.
The script works perfectly fine, on one database, but I will need to make several changes, to ALL databases which will simply take far too long.
I need to be able to run these commands across every database at once, rather than one database at a time.
My script, as it works currently on a single database:
UPDATE wp_posts SET post_content = REPLACE(post_content, 'http://www.old-domain.com', 'http://mixudo.com');
Many thanks

Try executing this query:
SELECT CONCAT('UPDATE ',
schema_name, '.\'wp_posts\' SET \'post_content\' = REPLACE(post_content, \'http://www.old-domain.com\', \'http://mixudo.com\');')
FROM information_schema.schemata
WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','phpmyadmin', 'webauth');
and then reexecuting the result.
Source: https://dba.stackexchange.com/a/20251

Create a list of database names with usernames/passwords that you need the script to be executed on
For each database in this list do:
Log into that database and select it
Run the script on that database
That is the only way to do your task safely.

You can get a list of databases on a mysql server using the SHOW DATABASES command. Using that as input you can write a shell script in whatever language you are capable that will foreach() through the list of databases, and running the UPDATE statement on each, by executing
use DBNAME;
Where DBNAME is the variable in the foreach. The update statement should work the same on all the databases, as I assume each db has the same set of tables with the same tablenames in each.
To Ed Heal's point, this also assumes you're using the root/admin user for the server so that it will have rights to update all the tables.

Related

query to replace term in all tables of database

I want to search for http://example.com and replace with https://example.com.
I know I can target a specific table and column with this approach:
UPDATE table_name SET post_content = REPLACE(column_name, 'http://example.com', 'https://example.com');
But how do I run a query which targets all tables/columns: the entire database?
Do a DB dump and open it as a text file. Find and replace. Save and then re-import.
As far as I know, I don't think you can use REPLACE on all tables in one query.
There a two ways to do it. The first is to create SQL UPDATE via the information_schema and execute it as prepared statement. this is much work.
you must look at each column if you can do a replace, so you must ignore INTS and ENUMs etc.
The second way is not a real SQL change, but it works: Generate a full SQL-Dump from your database and make the changes in this file via editor or via commandline with AWK or SED. After this you can import the changed file

Trying to copy entire MySQL schema using SQL commands

After searching SO, I found answers to the following:
How to copy an entire MySQL schema using mysqldump
How to copy an entire MySQL schema using PHP
How to copy an entire MySQL schema using the enterprise edition of MySQL
How to copy an entire Microsoft SQL Server schema using the menus.
I also found a few hints about copying a MySQL schema using SQL commands.
My question: If I use the following SQL commands to copy a MySQL schema, what parts of the old schema would not be copied? Indexes? Constraints? Views? Anything else?
CREATE SCHEMA new_schema DEFAULT CHARACTER SET utf8;
CREATE TABLE new_schema.table1 LIKE old_schema.table1;
CREATE TABLE new_schema.table2 LIKE old_schema.table2;
CREATE TABLE new_schema.table3 LIKE old_schema.table3;
...;
INSERT INTO new_schema.table1 SELECT * FROM old_schema.table1;
INSERT INTO new_schema.table2 SELECT * FROM old_schema.table2;
INSERT INTO new_schema.table3 SELECT * FROM old_schema.table3;
...;
The CREATE TABLE ... LIKE will take care of indexes and constraints.
You should take care to SET FOREIGN_KEY_CHECKS=0 while you run this, because if table1 has a foreign key to table2, then creating table1 will fail. Likewise inserting data into the tables in the wrong order will fail.
Your script does not cover:
Views
Triggers
Stored procedures
Stored functions
Events
There are no CREATE... LIKE... statements for these other objects. You'll have to use SHOW CREATE... and then run it against in the context of the new schema. See the various SHOW CREATE... statements here: http://dev.mysql.com/doc/refman/5.6/en/show.html
I also caution that the way you INSERT INTO... SELECT FROM... will work, but can fill up your rollback segment if the table is very large. Tools like pt-archiver try to copy tables in batches, ascending along the primary key, to avoid this problem.
I think routines can't be copied directly with sql commands (as far as I know there's not such anything like create procedure myProc like old.myProc).
I would recommend you use mysqldump, since it takes care of copying everything, including the data (if you don't want to copy the data, you can use the -d switch to prevent creating the insert statements).
If you want to create a "template" (a database that is exactly like another database, but without the data), you can use the following:
mysqldump [connectionParameters] -d -R -v yourOldDatabase > databaseTemplate.sql
The options explained:
[connectionParameters]: host, user and password
-d: Don't copy data
-R: Include routines in the dump
-v: Output what mysqldump is doing to the console
You can open this "light" sql script to check how the objects were created.
Hope this helps

Creating sql connections multiple times in loop causes to drop connection

I have one csv file. I am reading userId from it.It has around 30,000 users.
I have created one shell script to read that csv and search for that users in mysql database
and use that info to grab user related data from other tables.
I am running follwing kinds of query multiple times
mysql -uUserId -ppwd -hlocalhost -Pportno databaseName -e "Select *from UserInfo where UserName='Test'"
Its causing to drop the mysql connection after certain entries and automatically reconnecting.
Some entires get searched and some entries not.
Does Select query in loop for multiple times cause this problem
Any solution for it.

Changing current mysql database in a procedure?

For our system we are using multiple databases with the same structure. For example when we have 1000 customers, there will be 1000 databases. We've chosen to give each customers his own database, so we can delete all his data at once without any hassle.
Now I have to update the database structure several times a year. So I began to write a stored procedure which loops through all schemas. But I got stuck with executing a dynamic USE statement.
My code is as follows:
DECLARE V_SCHEMA VARCHAR(100);
SET V_SCHEMA = 'SomeSchemaName';
SET #QUERYSTRING = CONCAT('USE ', V_SCHEMA);
PREPARE S FROM #QUERYSTRING;
EXECUTE S;
DEALLOCATE PREPARE S;
When I execute this code I get an error which says Error Code: 1295. This command is not supported in the prepared statement protocol yet. So I assume that I cannot change the active database in a procedure.
I have searched the internet, but the only thing I found was creating a string of each alter query and prepare/execute/deallocate it. I hope there is a better solution for this. I could write a shell script that loops through the schemas and executes a SQL file on them, but I prefer a stored procedure that takes care of this.
Does anyone know how to make this work?
Thank you for your help!
EDIT: I use the latest stable version of MySQL 5.6
If there are some known databases, then try to write a CASE.
Otherwise, do not execute USE statement using prepared statements; instead, build other statements (SELECT, INSERT, UPDATE, ...) with full name - <database name> + '.' + <object name>, and execute them using prepared statements.
If you put your structure changes into a stored procedure in a temporary schema, you can do this within a Workbench SQL window.
You can build your iteration script using a query against the information_schema, e.g.
SELECT GROUP_CONCAT(CONCAT('USE ',schema_name,'; CALL tmp.Upgrade')
SEPARATOR ';\n') AS BldCode
FROM information_schema.schemata
WHERE schema_name NOT IN
('information_schema', 'performance_schema', 'mysql', 'sakila', 'world', 'tmp')
Since you cannot execute this as a prepared statement, you can copy the SQL result into a new SQL window, and run that.
Please note that the structure changes stored procedure would need to operate on the current schema, rather than specifying schemas.

Is it possible to delete all databases that were created by a specific user?

Is it possible to delete all databases that were created by a specific user?
Looking at MySQL's DELETE DATABASE syntax, it seems impossible via MySQL itself. However, you could use 3rd party application that queries:
SELECT db FROM mysql.db WHERE user = "<user>"
to get a list of user's databases, then loop over the result to query delete database above.