Skip to content

Commit fcf1ab9

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

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

Python_MySQL_P4.ipynb

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
4+
"metadata": {
5+
"colab": {
6+
"provenance": [],
7+
"authorship_tag": "ABX9TyPnDxcB6YsEhL/xN+ATAsX4",
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_P4.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 extract data from a MySQL database, manipulate it using JSON parsing, and update the database with the manipulated data. The script uses PyMySQL to connect to the database, execute SQL queries, and commit changes. In this project inside a column named as Value which contain json data so in place of that data i am updating that with the media key value of json data. For example if json data is like {\"name\":\"John\",\"media\":\"abc.com\"} so this code will update whole json data to media key value which is here \"abc.com\"."
34+
],
35+
"metadata": {
36+
"id": "L_PmSgzKlTzk"
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 first part of the script sets up the connection details for the MySQL database and creates a connection object using PyMySQL’s connect function. The host, user, password, and db arguments are passed to this function to specify the connection details.\n",
47+
"\n",
48+
"**Step 2: Query data from the table**\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 selects the id and Value columns from the oldtable table in the database. The execute method of the cursor object is called with this query as its argument, and the results are fetched using the fetchall method.\n",
51+
"\n",
52+
"**Step 3: Extract and manipulate data**\n",
53+
"\n",
54+
"The script then loops through each row in the results and extracts the values of the id and Value columns. If the value in the Value column is not NULL, it is parsed as JSON data using Python’s built-in json module. The script then loops through each dictionary in this JSON data and checks if it contains a key named 'media'. If this key is found, its value is extracted and used to update the value in the Value column of the current row in the database.\n",
55+
"\n",
56+
"**Step 4: Update data in the database**\n",
57+
"\n",
58+
"To update the value in the Value column, another SQL query is defined that uses an UPDATE statement to set the value of this column to the extracted media value for rows where the value of the id column matches the current row’s id. This query is executed using the cursor’s execute method, which takes two arguments: the query string and a tuple of values to substitute into placeholders in the query.\n",
59+
"\n",
60+
"**Step 5: Commit changes and close connection**\n",
61+
"\n",
62+
"After all rows have been processed, any changes made to the database are committed by calling the connection object’s commit method. Finally, both cursor and connection objects are closed by calling their respective close methods."
63+
],
64+
"metadata": {
65+
"id": "mOavJAQKobTL"
66+
}
67+
},
68+
{
69+
"cell_type": "code",
70+
"execution_count": null,
71+
"metadata": {
72+
"id": "itH7uulflS8_"
73+
},
74+
"outputs": [],
75+
"source": [
76+
"import pymysql\n",
77+
"import json\n",
78+
"\n",
79+
"# Connect to the database\n",
80+
"connection = pymysql.connect(host='yourhost',\n",
81+
" user='youruser',\n",
82+
" password='yourpassword@123',\n",
83+
" db='yourdatabasename')\n",
84+
"\n",
85+
"try:\n",
86+
" with connection.cursor() as cursor:\n",
87+
" # Query the data from the table\n",
88+
" sql = \"SELECT id, Value FROM oldtable\"\n",
89+
" cursor.execute(sql)\n",
90+
" results = cursor.fetchall()\n",
91+
"\n",
92+
" # Loop through the results and extract the value of the media key\n",
93+
" for row in results:\n",
94+
" id = row[0]\n",
95+
" col = row[1]\n",
96+
"\n",
97+
" # Check if the value in the col column is NULL\n",
98+
" if col is not None:\n",
99+
" try:\n",
100+
" data = json.loads(col)\n",
101+
"\n",
102+
" # Loop through the list of dictionaries\n",
103+
" for item in data:\n",
104+
" # Check if the media key exists in the dictionary\n",
105+
" if 'media' in item:\n",
106+
" media = item['media']\n",
107+
"\n",
108+
" # Update the value in the TRF column\n",
109+
" sql = \"UPDATE oldtable SET Value = %s WHERE id = %s\"\n",
110+
" cursor.execute(sql, (media, id))\n",
111+
" except json.decoder.JSONDecodeError:\n",
112+
" print(f\"Error: Unable to parse JSON data for row with id {id}\")\n",
113+
"\n",
114+
" # Commit the changes to the database\n",
115+
" connection.commit()\n",
116+
"finally:\n",
117+
" connection.close()\n"
118+
]
119+
}
120+
]
121+
}

0 commit comments

Comments
 (0)