Skip to content

Commit 2a20e9e

Browse files
committed
Created using Colaboratory
1 parent 41f4fde commit 2a20e9e

File tree

1 file changed

+266
-0
lines changed

1 file changed

+266
-0
lines changed

Python_MySQL_P7.ipynb

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
4+
"metadata": {
5+
"colab": {
6+
"provenance": [],
7+
"authorship_tag": "ABX9TyOMWccrgqPZiR/yOJ6znN6K",
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_P7.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+
"\n",
34+
"This code is written in Python and uses the mysql.connector library to connect to a MySQL database. The purpose of the code is to extract data from an existing table in the database, transform it, and insert it into a new table.\n",
35+
" This code is taking values and their corresponding IDs from an existing table in a MySQL database. It then creates a new table and checks which column each ID belongs to in the new table. Based on this information, it inserts the values into the appropriate columns of the new table.\n"
36+
],
37+
"metadata": {
38+
"id": "UwA4EsqLhZs0"
39+
}
40+
},
41+
{
42+
"cell_type": "markdown",
43+
"source": [
44+
"**Import the mysql.connector library:** This library is used to connect to a MySQL database from Python."
45+
],
46+
"metadata": {
47+
"id": "qMphP1ukk5yg"
48+
}
49+
},
50+
{
51+
"cell_type": "code",
52+
"execution_count": null,
53+
"metadata": {
54+
"id": "0SaahQishW9K"
55+
},
56+
"outputs": [],
57+
"source": [
58+
"import mysql.connector"
59+
]
60+
},
61+
{
62+
"cell_type": "markdown",
63+
"source": [
64+
"**Establish a connection to the MySQL database:** Use the connect method from the mysql.connector library and provide the necessary credentials such as host, user, password, and database name."
65+
],
66+
"metadata": {
67+
"id": "0Xg0nukfk_-U"
68+
}
69+
},
70+
{
71+
"cell_type": "code",
72+
"source": [
73+
"mydb = mysql.connector.connect(\n",
74+
" host=\"yourhost\",\n",
75+
" user=\"youruser\",\n",
76+
" password=\"yourpassword@123\",\n",
77+
" database=\"yourdatabasename\"\n",
78+
")\n"
79+
],
80+
"metadata": {
81+
"id": "KDCwALPvlGdn"
82+
},
83+
"execution_count": null,
84+
"outputs": []
85+
},
86+
{
87+
"cell_type": "markdown",
88+
"source": [
89+
"**Create a cursor object:** Use the cursor method of the connection object to create a cursor object. This cursor is used to execute SQL queries on the database."
90+
],
91+
"metadata": {
92+
"id": "No37tiLslOHP"
93+
}
94+
},
95+
{
96+
"cell_type": "code",
97+
"source": [
98+
"mycursor = mydb.cursor()\n"
99+
],
100+
"metadata": {
101+
"id": "pPCqwwS9lSDm"
102+
},
103+
"execution_count": null,
104+
"outputs": []
105+
},
106+
{
107+
"cell_type": "markdown",
108+
"source": [
109+
"**Define lists of IDs for each column in the new table:** Define lists of IDs that correspond to each column in a new table that will be created. These lists are used later in the code to extract values from an existing table and insert them into the new table.\n"
110+
],
111+
"metadata": {
112+
"id": "1LVXA_MzlUfI"
113+
}
114+
},
115+
{
116+
"cell_type": "code",
117+
"source": [
118+
"name_ids = ['1', '2', '3', '4', '5']\n",
119+
"phone_no_ids = ['6', '7', '8', '9', '10']\n",
120+
"date_of_birth_ids = ['11', '12', '13', '14', '15']\n",
121+
"age_ids = ['16', '17', '18', '19', '20']\n"
122+
],
123+
"metadata": {
124+
"id": "Jocl6gTXlgrf"
125+
},
126+
"execution_count": null,
127+
"outputs": []
128+
},
129+
{
130+
"cell_type": "markdown",
131+
"source": [
132+
"**Create a new table in the database:** Use the execute method of the cursor object and provide an SQL query to create a new table with the desired columns."
133+
],
134+
"metadata": {
135+
"id": "qA6Gwmcqlifb"
136+
}
137+
},
138+
{
139+
"cell_type": "code",
140+
"source": [
141+
"mycursor.execute(\"CREATE TABLE newtable (`Name` VARCHAR(255), `Phone No` VARCHAR(200), `Date of Birth` VARCHAR(300), `Age` VARCHAR(25)\")\n"
142+
],
143+
"metadata": {
144+
"id": "G6lba2deloo6"
145+
},
146+
"execution_count": null,
147+
"outputs": []
148+
},
149+
{
150+
"cell_type": "markdown",
151+
"source": [
152+
"**Construct an SQL query to select values from an existing table:** Construct an SQL query to select values and their corresponding IDs from an existing table. The query uses placeholders for the IDs, which are later replaced with the actual values using string formatting."
153+
],
154+
"metadata": {
155+
"id": "KWCndBs5lvLa"
156+
}
157+
},
158+
{
159+
"cell_type": "code",
160+
"source": [
161+
"query = \"SELECT IDs, Value FROM tablename WHERE IDs IN (%s)\"\n",
162+
"_ids = name_ids + phone_no_ids + date_of_birth_ids + age_ids\n",
163+
"in_p = ', '.join(list(map(lambda x: '%s', _ids)))\n",
164+
"query = query % in_p\n"
165+
],
166+
"metadata": {
167+
"id": "bbD4Vp4Rl2C9"
168+
},
169+
"execution_count": null,
170+
"outputs": []
171+
},
172+
{
173+
"cell_type": "markdown",
174+
"source": [
175+
"**Execute the query and fetch the results:** Execute the query using the execute method of the cursor object, providing the query and a tuple of IDs as arguments. Fetch the results of the query using the fetchall method of the cursor object."
176+
],
177+
"metadata": {
178+
"id": "XUsHETXpl4Vd"
179+
}
180+
},
181+
{
182+
"cell_type": "code",
183+
"source": [
184+
"mycursor.execute(query, tuple(_ids))\n",
185+
"results = mycursor.fetchall()\n"
186+
],
187+
"metadata": {
188+
"id": "Fz4AckXnmHRt"
189+
},
190+
"execution_count": null,
191+
"outputs": []
192+
},
193+
{
194+
"cell_type": "markdown",
195+
"source": [
196+
"**Initialize an empty dictionary to store row data:** Initialize an empty dictionary to store row data for insertion into the new table."
197+
],
198+
"metadata": {
199+
"id": "XEsH0oIZmJgy"
200+
}
201+
},
202+
{
203+
"cell_type": "code",
204+
"source": [
205+
"row_data = {}"
206+
],
207+
"metadata": {
208+
"id": "XxLJ8frqmPI4"
209+
},
210+
"execution_count": null,
211+
"outputs": []
212+
},
213+
{
214+
"cell_type": "markdown",
215+
"source": [
216+
"**Iterate over the results and insert values into the new table:** Iterate over the results of the query, checking if each ID is in one of the predefined lists of IDs. If it is, determine which column in the new table it corresponds to and add it to the row data dictionary.\n",
217+
"Once all values for a row have been added to the row data dictionary, construct an INSERT statement using string formatting to insert the row into the new table. Execute the statement using the execute method of the cursor object, providing the INSERT statement and a tuple of values as arguments. Commit the changes to the database using the commit method of the connection object.\n",
218+
"\n",
219+
"This process is repeated for all rows in the results until all data has been inserted into the new table"
220+
],
221+
"metadata": {
222+
"id": "S4D0vS7XmR4t"
223+
}
224+
},
225+
{
226+
"cell_type": "code",
227+
"source": [
228+
"for _id, value in results:\n",
229+
" if _id in name_ids:\n",
230+
" # Start a new row if a IDs from name_ids is encountered\n",
231+
" if row_data:\n",
232+
" columns = ', '.join([f'`{column}`' for column in row_data.keys()])\n",
233+
" values = tuple(row_data.values())\n",
234+
" placeholders = ', '.join(['%s'] * len(values))\n",
235+
" mycursor.execute(f\"INSERT INTO newtable ({columns}) VALUES ({placeholders})\", values)\n",
236+
" mydb.commit()\n",
237+
" row_data = {}\n",
238+
"\n",
239+
" column_name = \"Name\"\n",
240+
" elif _id in phone_no_ids:\n",
241+
" column_name = \"Phone No\"\n",
242+
" elif _id in date_of_birth_ids:\n",
243+
" column_name = \"Date of Birth\"\n",
244+
" elif _id in age_ids:\n",
245+
" column_name = \"Age\"\n",
246+
" else:\n",
247+
" continue\n",
248+
"\n",
249+
" row_data[column_name] = value\n",
250+
"\n",
251+
"# Insert last row of data into new table\n",
252+
"if row_data:\n",
253+
" columns = ', '.join([f'`{column}`' for column in row_data.keys()])\n",
254+
" values = tuple(row_data.values())\n",
255+
" placeholders = ', '.join(['%s'] * len(values))\n",
256+
" mycursor.execute(f\"INSERT INTO newtable ({columns}) VALUES ({placeholders})\", values)\n",
257+
" mydb.commit()\n"
258+
],
259+
"metadata": {
260+
"id": "iO6vVEqPmfwY"
261+
},
262+
"execution_count": null,
263+
"outputs": []
264+
}
265+
]
266+
}

0 commit comments

Comments
 (0)