Skip to content

Commit 3d55ded

Browse files
committed
Created using Colaboratory
1 parent ca01b70 commit 3d55ded

File tree

1 file changed

+141
-0
lines changed

1 file changed

+141
-0
lines changed

Python_MySQL_P5.ipynb

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
4+
"metadata": {
5+
"colab": {
6+
"provenance": [],
7+
"authorship_tag": "ABX9TyMvJ95CWNzXGH2b1EKVScEn",
8+
"include_colab_link": true
9+
},
10+
"kernelspec": {
11+
"name": "python3",
12+
"display_name": "Python 3"
13+
},
14+
"language_info": {
15+
"name": "python"
16+
}
17+
},
18+
"cells": [
19+
{
20+
"cell_type": "markdown",
21+
"metadata": {
22+
"id": "view-in-github",
23+
"colab_type": "text"
24+
},
25+
"source": [
26+
"<a href=\"https://colab.research.google.com/github/Animeshcoder/MySQL-Python/blob/main/Python_MySQL_P5.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
27+
]
28+
},
29+
{
30+
"cell_type": "markdown",
31+
"source": [
32+
"### **Introduction:**\n",
33+
"This project is a Python script that demonstrates how to search for URLs in a MySQL database. The script defines a search_database function that takes the connection details for a MySQL database as arguments and returns a list of results. This function uses PyMySQL to connect to the database, execute SQL queries, and fetch results. Best part is that you don't need to get the name of table where the URLs are present this code will execute all table and all columns after that it will return all matching rows.\n"
34+
],
35+
"metadata": {
36+
"id": "CB65iYVipDz4"
37+
}
38+
},
39+
{
40+
"cell_type": "markdown",
41+
"source": [
42+
"### **Involved Steps:**\n",
43+
"\n",
44+
"**Step 1: Connect to the database**\n",
45+
"\n",
46+
"The search_database function starts by setting up the connection details for the MySQL database and creating a connection object using PyMySQL’s connect function. The host, user, password, and database arguments are passed to this function to specify the connection details.\n",
47+
"\n",
48+
"**Step 2: Query data from the tables**\n",
49+
"\n",
50+
"Next, a cursor object is created using the cursor method of the connection object. This cursor is used to execute an SQL query that retrieves a list of all tables in the database using the SHOW TABLES statement. The table names are stored in a list.\n",
51+
"\n",
52+
"*The function then loops through each table in this list and performs the following steps:*\n",
53+
"\n",
54+
"*Get list of columns:* The code retrieves a list of all columns of type varchar in the current table by executing an SQL query that selects the COLUMN_NAME column from the INFORMATION_SCHEMA.COLUMNS table where the value of the TABLE_NAME column matches the current table name and the value of the DATA_TYPE column is 'varchar'. The column names are stored in a list.\n",
55+
"\n",
56+
"*Build WHERE clause:* The code builds a WHERE clause for an SQL SELECT statement that searches for rows in the current table that contain URLs in any varchar column. This is done by joining together multiple conditions using the OR operator, where each condition uses a regular expression to match columns that contain URLs.\n",
57+
"\n",
58+
"*Execute SELECT statement:* If there are any varchar columns in the current table, the code executes an SQL SELECT statement using the built WHERE clause to search for rows in the current table that contain URLs in any varchar column. Any matching rows are added to a list of results.\n",
59+
"\n",
60+
"**Step 3: Close connection and return results**\n",
61+
"\n",
62+
"After all tables have been searched, both cursor and connection objects are closed by calling their respective close methods. Finally, the list of results is returned to the caller."
63+
],
64+
"metadata": {
65+
"id": "OpHs5L1dq_9m"
66+
}
67+
},
68+
{
69+
"cell_type": "code",
70+
"execution_count": null,
71+
"metadata": {
72+
"id": "QWW8xsA_pB3j"
73+
},
74+
"outputs": [],
75+
"source": [
76+
"import pymysql\n",
77+
"\n",
78+
"def search_database(host, user, password, database):\n",
79+
" # Set up the connection\n",
80+
" conn = pymysql.connect(\n",
81+
" host=host,\n",
82+
" user=user,\n",
83+
" password=password,\n",
84+
" database=database\n",
85+
" )\n",
86+
"\n",
87+
" # Create a cursor\n",
88+
" cursor = conn.cursor()\n",
89+
"\n",
90+
" # Get the list of tables\n",
91+
" cursor.execute(\"SHOW TABLES\")\n",
92+
" tables = [row[0] for row in cursor.fetchall()]\n",
93+
"\n",
94+
" # Search for the value in all columns of all tables\n",
95+
" results = []\n",
96+
" for table in tables:\n",
97+
" # Get the list of columns\n",
98+
" table_escaped = conn.escape_string(table)\n",
99+
" cursor.execute(f\"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table_escaped}' AND DATA_TYPE = 'varchar'\")\n",
100+
" columns = [row[0] for row in cursor.fetchall()]\n",
101+
"\n",
102+
" # Build the WHERE clause\n",
103+
" where_clause = ' OR '.join([f\"`{column}` REGEXP 'https?://[^/\\\\\\\\s]+' \" for column in columns])\n",
104+
"\n",
105+
" # Check if the where_clause is not empty\n",
106+
" if where_clause:\n",
107+
" # Execute the SELECT statement\n",
108+
" query = f\"SELECT * FROM `{table_escaped}` WHERE {where_clause}\"\n",
109+
" print(f\"Executing query: {query}\")\n",
110+
" cursor.execute(query)\n",
111+
"\n",
112+
" # Fetch the results\n",
113+
" rows = cursor.fetchall()\n",
114+
" if rows:\n",
115+
" results.append((table, rows))\n",
116+
"\n",
117+
" # Close the cursor and connection\n",
118+
" cursor.close()\n",
119+
" conn.close()\n",
120+
"\n",
121+
" return results\n",
122+
"\n",
123+
"# Example usage\n",
124+
"results = search_database(\n",
125+
" host='yourhost',\n",
126+
" user='youruser',\n",
127+
" password='yourpassword@123',\n",
128+
" database='yourdatabasename'\n",
129+
")\n",
130+
"\n",
131+
"for table, rows in results:\n",
132+
" print(f\"Found {len(rows)} match(es) in table '{table}':\")\n",
133+
" for row in rows:\n",
134+
" print(row)\n",
135+
"\n",
136+
"# Note: In MySQL queries if your column or table or database name has speces inbetween then then you have to use backtick in place of quotes for example i have used `{table_escaped}` and `{column}`\n",
137+
"# because i don't know about the table names and column names so it can be anything."
138+
]
139+
}
140+
]
141+
}

0 commit comments

Comments
 (0)