728x90
Insert multi rows.
cursor.executemany() 함수를 활용하여 다중 행을 Insert하는 예제입니다.
data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s) "
cursor.executemany(stmt, data)
다음과 같은 SQL실행되게 됩니다.
INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')
Update multi rows.
data = [
(1, date(2005, 2, 12)),
(2, date(2006, 5, 23)),
(3, date(2010, 10, 3)),
]
stmt = "UPDATE employees SET hire_date = %s WHERE id = %s "
cur.executemany(stmt, data)
Insert & Update
import MySQLdb
def update_many(data_list=None, mysql_table=None):
"""
Updates a mysql table with the data provided. If the key is not unique, the
data will be inserted into the table.
The dictionaries must have all the same keys due to how the query is built.
Param:
data_list (List):
A list of dictionaries where the keys are the mysql table
column names, and the values are the update values
mysql_table (String):
The mysql table to be updated.
"""
# Connection and Cursor
conn = MySQLdb.connect(host='localhost',
database='dbname',
user='uid',
password='pass')
cur = conn.cursor()
query = ""
values = []
for data_dict in data_list:
if not query:
columns = ', '.join('`{0}`'.format(k) for k in data_dict)
duplicates = ', '.join('{0}=VALUES({0})'.format(k) for k in data_dict)
place_holders = ', '.join('%s'.format(k) for k in data_dict)
query = "INSERT INTO {0} ({1}) VALUES ({2})".format(mysql_table, columns, place_holders)
query = "{0} ON DUPLICATE KEY UPDATE {1}".format(query, duplicates)
v = data_dict.values()
values.append(v)
try:
cur.executemany(query, values)
except MySQLdb.Error, e:
try:
print"MySQL Error [%d]: %s" % (e.args[0], e.args[1])
except IndexError:
print "MySQL Error: %s" % str(e)
conn.rollback()
return False
conn.commit()
cur.close()
conn.close()
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='electronics',
user='pynative',
password='pynative@#29')
cursor = connection.cursor()
sql_update_query = """Update Laptop set Price = %s where id = %s"""
# multiple records to be updated in tuple format
records_to_update = [(3000, 3), (2750, 4)]
cursor.executemany(sql_update_query, records_to_update)
connection.commit()
print(cursor.rowcount, "Records of a laptop table updated successfully")
except mysql.connector.Error as error:
print("Failed to update records to database: {}".format(error))
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")
728x90
'Data Science > Python' 카테고리의 다른 글
[Python] Pandas replace (0) | 2022.02.22 |
---|---|
[Python] Mysql Connection Pooling 만들기 (0) | 2022.02.16 |
[Python] 대용량 데이터 처리 및 분석을 위한 PyArrow (Apache Arrow) (0) | 2022.02.16 |
[PYTHON] 유용한 정규식 모음 (0) | 2021.09.16 |
[ETL실전] Python으로 CSV 파일을 DB(Mysql)에 임포트하기 #1 (0) | 2021.08.03 |
최근댓글