import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("ram1", "btm 55")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table.
mydb.commit()
-----------------
Insert Multiple Rows
To insert multiple rows into a table, use the executemany() method.
The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('ramesh', 'fLowstreet 4'),
('sureesh', 'bApple st 652'),
('chiru', 'eMountain 21'),
('kumarl', 'gValley 345'),
('praveen', 'fOcean blvd 2'),
('anji', 'bGreen Grass 1'),
('hari', 'nSky st 331'),
('nalini', 'nOne way 98'),
('nani', 'uYellow Garden 2'),
('koti', 'wPark Lane 38'),
('gopi', 'qCentral st 954'),
('ramu', 'rMain Road 989'),
('madhu', 'qqwSideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
------------------
Get Inserted ID
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("mahesh", "bantumilli")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
No comments:
Post a Comment
Note: only a member of this blog may post a comment.