Search text in fields in every table of a MySQL database

前端 未结 24 1948
梦谈多话
梦谈多话 2020-11-22 06:23

I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

SELECT * FROM * WHERE * LIKE \'%stuff%\'
         


        
24条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:36

    In case 23 answers is not enough, here are 2 more... Depending on database structure and content, you may find one them to actually be a quick and simple solution.

    For fans of shell one-liners, here is a long one (actually on 2 lines to use variables):

    cmd='mysql -u Username -pYour_Password -D Your_Database' # <-- Adapt this
    
    $cmd -s -e 'SHOW TABLES' | while read table; do echo "=== $table ==="; $cmd -B -s -e "SELECT * FROM $table" | grep 'Your_Search'; done
    

    Or on multiple lines to make it more readable:

    $cmd -s -e 'SHOW TABLES' \
    | while read table; do
        echo "=== $table ===";
        $cmd -B -s -e "SELECT * FROM $table" \
        | grep 'Your_Search';
      done
    
    • -s (--silent) is to suppress the column name headers

    • -B (--batch) escapes special characters like newlines, so we get the whole record when using grep

    And for Perl fans, this will let you use regular expressions:

    # perl -MDBI -le '($db,$u,$p)=@ARGV; $dbh=DBI->connect("dbi:mysql:dbname=$db",$u,$p); foreach $table ($dbh->tables()) {print "$table\n"; foreach $r ($dbh->selectall_array("SELECT * FROM $table")) {$_=join("\t", @$r); print $_ if (/Your_Regex/);}}' Your_Database Username Your_Password
    

    Which in a "real" Perl script could be something like this:

    #!/usr/bin/perl
    
    use strict;
    use open qw(:std :utf8);
    
    use DBI;
    
    my $db_host  = 'localhost';
    my $db       = 'Your_Database';
    my $db_user  = 'Username';
    my $db_pass  = 'Your_Password';
    
    my $search    = qr/Your_regex_Search/;
    
    
    # https://metacpan.org/pod/DBD::mysql
    my $dbh = DBI->connect( "dbi:mysql:dbname=$db;host=$db_host", $db_user, $db_pass,
                            { mysql_enable_utf8mb4 => 1 }
    ) or die "Can't connect: $DBI::errstr\n";
    
    
    foreach my $table ( $dbh->tables() ) {
        my $sth = $dbh->prepare("SELECT * FROM $table")
            or die "Can't prepare: ", $dbh->errstr;
    
        $sth->execute
            or die "Can't execute: ", $sth->errstr;
    
        my @results;
    
        while (my @row = $sth->fetchrow()) {
            local $_ = join("\t", @row);
            if ( /$search/ ) {
                push @results, $_;
            }
        }
    
        $sth->finish;
    
        next unless @results;
    
        print "*** TABLE $table :\n",
              join("\n---------------\n", @results),
              "\n" . "=" x 20 . "\n";
    }
    
    $dbh->disconnect;
    

提交回复
热议问题