-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw3school_pythonmysqlinsert.py
More file actions
70 lines (48 loc) · 1.55 KB
/
w3school_pythonmysqlinsert.py
File metadata and controls
70 lines (48 loc) · 1.55 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Python MySQL Insert Into Table
# Insert Into Table
# To fill a table in MySQL, use the "INSERT INTO" statement.
import mysql.connector # import MySQL Connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "mahanta1",
database = "mydatabase"
)
mycursor = mydb.cursor()
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# val1 = ("Peter", "4293 Southampton Drive")
# mycursor.execute(sql, val1)
# mydb.commit()
# print(mycursor.rowcount, "record inserted.")
# Insert Multiple Rows
# To insert multiple rows into a table, use the executemany() method.
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('John', 'Highway 21'),
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
# Get Inserted ID
# You can get the id of the row you just inserted by asking the cursor object.
# Example - Insert one row, and return the ID:
"""
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
"""