|
@@ -37,14 +37,14 @@ class MySQLManager:
|
|
|
finally:
|
|
|
conn.close()
|
|
|
|
|
|
- def batch_insert(self, table, data, columns=None):
|
|
|
+ def batch_insert(self, table, data, columns=None, ignore=False):
|
|
|
"""
|
|
|
table: table name, string
|
|
|
data: data, list[tuple] or list[dict]
|
|
|
columns: column names, list, required if data is list[tuple]
|
|
|
"""
|
|
|
if data is None or len(data) == 0:
|
|
|
- return
|
|
|
+ return None
|
|
|
conn = pymysql.connect(**self.config)
|
|
|
try:
|
|
|
if isinstance(data[0], dict):
|
|
@@ -56,10 +56,12 @@ class MySQLManager:
|
|
|
raise Exception("data length != column length")
|
|
|
columns_str = ','.join(columns)
|
|
|
placeholders_str = ','.join(['%s'] * len(data[0]))
|
|
|
+ ignore_keyword = 'IGNORE' if ignore else ''
|
|
|
with conn.cursor() as cursor:
|
|
|
- sql_str = f"INSERT INTO {table} ({columns_str}) VALUES ({placeholders_str})"
|
|
|
- cursor.executemany(sql_str, data)
|
|
|
+ sql_str = f"INSERT {ignore_keyword} INTO {table} ({columns_str}) VALUES ({placeholders_str})"
|
|
|
+ rows = cursor.executemany(sql_str, data)
|
|
|
conn.commit()
|
|
|
+ return rows
|
|
|
except pymysql.MySQLError as e:
|
|
|
print(f"Error in batch_insert: {e}")
|
|
|
conn.rollback()
|