Last active
February 22, 2024 15:10
-
-
Save macielti/aa8bfb78c766886cf96c0ce112908b7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
try: | |
connection = mysql.connector.connect(host='foo.bar.com.br', database='foobar', user='foo', password='foobar2020') | |
# The string that you want to search. | |
seeked_value = "%8439742464%" # Like syntax | |
if connection.is_connected(): | |
db_Info = connection.get_server_info() | |
print("Connected to MySQL Server version ", db_Info) | |
# Get all tables and coluns that exists on database. | |
cursor = connection.cursor() | |
cursor.execute('''select | |
distinct c.TABLE_NAME, | |
c.COLUMN_NAME | |
from information_schema.`COLUMNS` c | |
where | |
c.TABLE_SCHEMA = "foobar" and | |
c.DATA_TYPE = "varchar";''') | |
records = cursor.fetchall() | |
print("Número de colunas =>", len(records)) | |
result_of_global_search = [] | |
# For each column on each table, we search for the desired value. | |
for n, record in enumerate(records): | |
table_name = record[0] | |
column_name = record[1] | |
query_string = f''' | |
select | |
* | |
from {table_name} | |
where | |
`{column_name}` like "{seeked_value}";''' | |
cursor.execute(query_string) | |
query_results_records = cursor.fetchall() | |
# show the progress of the search. | |
print(f"{n}/{len(records)} ({table_name},{column_name}) =>", query_results_records); | |
if len(query_results_records) > 0: | |
# when we found one column and table with the desired value, add the column, table and rows to a list. | |
result_of_global_search.append(f"{n} ({table_name},{column_name}) => {query_results_records}") | |
except Exception as e: | |
print("Error while connecting to MySQL =>", query_string, e) | |
else: | |
# Print the array that contains the result of the search. | |
print("\n\nFinal Result =>", "\n".join(result_of_global_search)) | |
finally: | |
if (connection.is_connected()): | |
cursor.close() | |
connection.close() | |
print("MySQL connection is closed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment