Skip to content

Commit cc4fa4a

Browse files
authored
Add files via upload
1 parent ed4b85e commit cc4fa4a

File tree

1 file changed

+371
-0
lines changed

1 file changed

+371
-0
lines changed
+371
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,371 @@
1+
# Introduction to MySQL Queries
2+
MySQL is a widely-used open-source relational database management system (RDBMS) that utilizes SQL (Structured Query Language) for managing and querying data. In Python, the **mysql-connector-python** library allows you to connect to MySQL databases and execute SQL queries, providing a way to interact with the database from within a Python program.
3+
4+
## Prerequisites
5+
* Python and MySQL Server must be installed and configured.
6+
* The library: **mysql-connector-python** must be installed.
7+
8+
## Establishing connection with server
9+
To establish a connection with the MySQL server, you need to import the **mysql.connector** module and create a connection object using the **connect()** function by providing the prompt server details as mentioned.
10+
11+
```python
12+
import mysql.connector
13+
14+
con = mysql.connector.connect(
15+
host ="localhost",
16+
user ="root",
17+
passwd ="12345"
18+
)
19+
20+
print((con.is_connected()))
21+
```
22+
Having established a connection with the server, you get the following output :
23+
```
24+
True
25+
```
26+
## Creating a Database [CREATE]
27+
To create a database, you need to execute the **CREATE DATABASE** query. The following code snippet demonstrates how to create a database named **GSSOC**.
28+
```python
29+
import mysql.connector
30+
31+
# Establish the connection
32+
conn = mysql.connector.connect(
33+
host="localhost",
34+
user="root",
35+
password="12345"
36+
)
37+
38+
# Create a cursor object
39+
cursor = conn.cursor()
40+
41+
# Execute the query to show databases
42+
cursor.execute("SHOW DATABASES")
43+
44+
# Fetch and print the databases
45+
databases = cursor.fetchall()
46+
for database in databases:
47+
print(database[0])
48+
49+
# Execute the query to create database GSSOC
50+
cursor.execute("CREATE DATABASE GSSOC")
51+
52+
print("\nAfter creation of the database\n")
53+
54+
# Execute the query to show databases
55+
cursor.execute("SHOW DATABASES")
56+
# Fetch and print the databases
57+
databases = cursor.fetchall()
58+
for database in databases:
59+
print(database[0])
60+
61+
cursor.close()
62+
conn.close()
63+
```
64+
You can observe in the output below, after execution of the query a new database named **GSSOC** has been created.
65+
#### Output:
66+
```
67+
information_schema
68+
mysql
69+
performance_schema
70+
sakila
71+
sys
72+
world
73+
74+
After creation of the database
75+
76+
gssoc
77+
information_schema
78+
mysql
79+
performance_schema
80+
sakila
81+
sys
82+
world
83+
```
84+
## Creating a Table in the Database [CREATE]
85+
Now, we will create a table in the database. We will create a table named **example_table** in the database **GSSOC**. We will execute **CREATE TABLE** query and provide the fields for the table as mentioned in the code below:
86+
```python
87+
import mysql.connector
88+
89+
# Establish the connection
90+
conn = mysql.connector.connect(
91+
host="localhost",
92+
user="root",
93+
password="12345"
94+
)
95+
# Create a cursor object
96+
cursor = conn.cursor()
97+
98+
# Execute the query to show tables
99+
cursor.execute("USE GSSOC")
100+
cursor.execute("SHOW TABLES")
101+
102+
# Fetch and print the tables
103+
tables = cursor.fetchall()
104+
print("Before creation of table\n")
105+
for table in tables:
106+
print(table[0])
107+
108+
create_table_query = """
109+
CREATE TABLE example_table (
110+
name VARCHAR(255) NOT NULL,
111+
age INT NOT NULL,
112+
email VARCHAR(255)
113+
)
114+
"""
115+
# Execute the query
116+
cursor.execute(create_table_query)
117+
118+
# Commit the changes
119+
conn.commit()
120+
121+
print("\nAfter creation of Table\n")
122+
# Execute the query to show tables in GSSOC
123+
cursor.execute("SHOW TABLES")
124+
125+
# Fetch and print the tables
126+
tables = cursor.fetchall()
127+
for table in tables:
128+
print(table[0])
129+
130+
cursor.close()
131+
conn.close()
132+
```
133+
#### Output:
134+
```
135+
Before creation of table
136+
137+
138+
After creation of Table
139+
140+
example_table
141+
```
142+
## Inserting Data [INSERT]
143+
To insert data in an existing table, the **INSERT INTO** query is used, followed by the name of the table in which the data needs to be inserted. The following code demonstrates the insertion of multiple records in the table by **executemany()**.
144+
```python
145+
import mysql.connector
146+
147+
# Establish the connection
148+
conn = mysql.connector.connect(
149+
host="localhost",
150+
user="root",
151+
password="12345"
152+
)
153+
# Create a cursor object
154+
cursor = conn.cursor()
155+
cursor.execute("USE GSSOC")
156+
# SQL query to insert data
157+
insert_data_query = """
158+
INSERT INTO example_table (name, age, email)
159+
VALUES (%s, %s, %s)
160+
"""
161+
162+
# Data to be inserted
163+
data_to_insert = [
164+
("John Doe", 28, "john.doe@example.com"),
165+
("Jane Smith", 34, "jane.smith@example.com"),
166+
("Sam Brown", 22, "sam.brown@example.com")
167+
]
168+
169+
# Execute the query for each data entry
170+
cursor.executemany(insert_data_query, data_to_insert)
171+
172+
conn.commit()
173+
cursor.close()
174+
conn.close()
175+
```
176+
## Displaying Data [SELECT]
177+
To display the data from a table, the **SELECT** query is used. The following code demonstrates the display of data from the table.
178+
```python
179+
import mysql.connector
180+
181+
# Establish the connection
182+
conn = mysql.connector.connect(
183+
host="localhost",
184+
user="root",
185+
password="12345"
186+
)
187+
# Create a cursor object
188+
cursor = conn.cursor()
189+
cursor.execute("USE GSSOC")
190+
191+
# SQL query to display data
192+
display_data_query = "SELECT * FROM example_table"
193+
194+
# Execute the query for each data entry
195+
cursor.execute(display_data_query)
196+
197+
# Fetch all the rows
198+
rows = cursor.fetchall()
199+
200+
# Print the column names
201+
column_names = [desc[0] for desc in cursor.description]
202+
print(column_names)
203+
204+
# Print the rows
205+
for row in rows:
206+
print(row)
207+
208+
cursor.close()
209+
conn.close()
210+
```
211+
#### Output :
212+
```
213+
['name', 'age', 'email']
214+
('John Doe', 28, 'john.doe@example.com')
215+
('Jane Smith', 34, 'jane.smith@example.com')
216+
('Sam Brown', 22, 'sam.brown@example.com')
217+
```
218+
## Updating Data [UPDATE]
219+
To update data in the table, **UPDATE** query is used. In the following code, we will be updating the email and age of the record where the name is John Doe.
220+
```python
221+
import mysql.connector
222+
223+
# Establish the connection
224+
conn = mysql.connector.connect(
225+
host="localhost",
226+
user="root",
227+
password="12345"
228+
)
229+
# Create a cursor object
230+
cursor = conn.cursor()
231+
cursor.execute("USE GSSOC")
232+
233+
# SQL query to display data
234+
display_data_query = "SELECT * FROM example_table"
235+
236+
# SQL Query to update data of John Doe
237+
update_data_query = """
238+
UPDATE example_table
239+
SET age = %s, email = %s
240+
WHERE name = %s
241+
"""
242+
243+
# Data to be updated
244+
data_to_update = (30, "new.email@example.com", "John Doe")
245+
246+
# Execute the query
247+
cursor.execute(update_data_query, data_to_update)
248+
249+
# Commit the changes
250+
conn.commit()
251+
252+
# Execute the query for each data entry
253+
cursor.execute(display_data_query)
254+
255+
# Fetch all the rows
256+
rows = cursor.fetchall()
257+
258+
# Print the column names
259+
column_names = [desc[0] for desc in cursor.description]
260+
print(column_names)
261+
262+
# Print the rows
263+
for row in rows:
264+
print(row)
265+
266+
cursor.close()
267+
conn.close()
268+
```
269+
#### Output:
270+
```
271+
['name', 'age', 'email']
272+
('John Doe', 30, 'new.email@example.com')
273+
('Jane Smith', 34, 'jane.smith@example.com')
274+
('Sam Brown', 22, 'sam.brown@example.com')
275+
```
276+
277+
## Deleting Data [DELETE]
278+
In this segment, we will Delete the record named "John Doe" using the **DELETE** and **WHERE** statements in the query. The following code explains the same and the observe the change in output.
279+
```python
280+
import mysql.connector
281+
282+
# Establish the connection
283+
conn = mysql.connector.connect(
284+
host="localhost",
285+
user="root",
286+
password="12345"
287+
)
288+
# Create a cursor object
289+
cursor = conn.cursor()
290+
cursor.execute("USE GSSOC")
291+
292+
# SQL query to display data
293+
display_data_query = "SELECT * FROM example_table"
294+
295+
# SQL query to delete data
296+
delete_data_query = "DELETE FROM example_table WHERE name = %s"
297+
298+
# Data to be deleted
299+
data_to_delete = ("John Doe",)
300+
301+
# Execute the query
302+
cursor.execute(delete_data_query, data_to_delete)
303+
304+
# Commit the changes
305+
conn.commit()
306+
307+
# Execute the query for each data entry
308+
cursor.execute(display_data_query)
309+
310+
# Fetch all the rows
311+
rows = cursor.fetchall()
312+
313+
# Print the column names
314+
column_names = [desc[0] for desc in cursor.description]
315+
print(column_names)
316+
317+
# Print the rows
318+
for row in rows:
319+
print(row)
320+
321+
cursor.close()
322+
conn.close()
323+
```
324+
#### Output:
325+
```
326+
['name', 'age', 'email']
327+
('Jane Smith', 34, 'jane.smith@example.com')
328+
('Sam Brown', 22, 'sam.brown@example.com')
329+
```
330+
## Deleting the Table/Database [DROP]
331+
For deleting a table, you can use the **DROP** query in the following manner:
332+
```python
333+
import mysql.connector
334+
335+
# Establish the connection
336+
conn = mysql.connector.connect(
337+
host="localhost",
338+
user="root",
339+
password="12345"
340+
)
341+
# Create a cursor object
342+
cursor = conn.cursor()
343+
cursor.execute("USE GSSOC")
344+
345+
# SQL query to delete the table
346+
delete_table_query = "DROP TABLE IF EXISTS example_table"
347+
348+
# Execute the query
349+
cursor.execute(delete_table_query)
350+
351+
# Verify the table deletion
352+
cursor.execute("SHOW TABLES LIKE 'example_table'")
353+
result = cursor.fetchone()
354+
355+
cursor.close()
356+
conn.close()
357+
358+
if result:
359+
print("Table deletion failed.")
360+
else:
361+
print("Table successfully deleted.")
362+
```
363+
#### Output:
364+
```
365+
Table successfully deleted.
366+
```
367+
Similarly, you can delete the database also by using the **DROP** and accordingly changing the query to be executed.
368+
369+
370+
371+

0 commit comments

Comments
 (0)