-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path43_MySQL_connect.py
More file actions
45 lines (35 loc) · 956 Bytes
/
43_MySQL_connect.py
File metadata and controls
45 lines (35 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"Write a Program to show MySQL database connectivity in python."
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1", # Loopback to self.
user="python",
password="python",
database="python"
)
mycursor = mydb.cursor(buffered=True)
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
# optional here
mycursor.execute(
"CREATE TABLE person (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), addr VARCHAR(255))")
sql = "INSERT INTO person (name, addr) VALUES (%s, %s)"
val = [
('Dev', 'Nagpur'),
('Patil', 'Delhi'),
('Kural', 'Patna'),
('George', 'Indore'),
]
mycursor.executemany(sql, val)
mydb.commit() # finalizes the connection
__OUTPUT__ = """
+----+--------+--------+
| id | name | addr |
+----+--------+--------+
| 1 | Dev | Nagpur |
| 2 | Patil | Delhi |
| 3 | Kural | Patna |
| 4 | George | Indore |
+----+--------+--------+
4 rows in set (0.01 sec)
"""