通常我使用手动查找替换文本在MySQL数据库使用phpMyAdmin。我现在厌倦了,我怎么能运行一个查询,在phpMyAdmin的整个表中找到和替换一个新的文本?
例如:查找关键字domain。例如,替换为www.domain.example。
通常我使用手动查找替换文本在MySQL数据库使用phpMyAdmin。我现在厌倦了,我怎么能运行一个查询,在phpMyAdmin的整个表中找到和替换一个新的文本?
例如:查找关键字domain。例如,替换为www.domain.example。
当前回答
把它放到一个php文件中,然后运行它,它应该做你想做的事情。
// Connect to your MySQL database.
$hostname = "localhost";
$username = "db_username";
$password = "db_password";
$database = "db_name";
mysql_connect($hostname, $username, $password);
// The find and replace strings.
$find = "find_this_text";
$replace = "replace_with_this_text";
$loop = mysql_query("
SELECT
concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
FROM
information_schema.columns
WHERE
table_schema = '{$database}'")
or die ('Cant loop through dbfields: ' . mysql_error());
while ($query = mysql_fetch_assoc($loop))
{
mysql_query($query['s']);
}
其他回答
最好你把它导出为SQL文件,用visual studio代码等编辑器打开,然后找到并重新排版你的文字。 我在1分钟内替换1gig文件SQL 16个字,总共是14600个字。 这是最好的办法。 替换后保存并再次导入。 不要忘记压缩它与zip导入。
另一种选择是为数据库中的每一列生成语句:
SELECT CONCAT(
'update ', table_name ,
' set ', column_name, ' = replace(', column_name,', ''www.oldDomain.example'', ''www.newDomain.example'');'
) AS statement
FROM information_schema.columns
WHERE table_schema = 'mySchema' AND table_name LIKE 'yourPrefix_%';
这将生成一个更新语句列表,然后您可以执行这些更新语句。
我发现的最简单的方法是将数据库转储到一个文本文件中,运行sed命令进行替换,然后将数据库重新加载回MySQL。
下面所有命令都是Linux下的bash命令。
转储数据库到文本文件
mysqldump -u user -p databasename > ./db.sql
执行sed命令查找/替换目标字符串
sed -i 's/oldString/newString/g' ./db.sql
重新加载数据库到MySQL
mysql -u user -p databasename < ./db.sql
容易peasy。
我相信“swapnesh”答案是最好的!不幸的是,我不能执行它在phpMyAdmin(4.5.0.2)谁虽然不合逻辑(并尝试了几件事),它一直说,一个新的语句被发现,没有分隔符被发现…
因此,我提出了以下解决方案,如果您遇到同样的问题,并且除了PMA之外没有其他访问数据库的方法,可能会很有用……
UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
要测试预期的结果,您可能需要使用:
SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
在有大小写字母的句子中, 我们可以使用二进制REPACE
UPDATE `table_1` SET `field_1` = BINARY REPLACE(`field_1`, 'find_string', 'replace_string')