Ich muss Millionen von Zeile in MySQL aktualisieren. Ich verwende zur Zeit for-Schleife, um eine Abfrage auszuführen. Um das Update schneller zu machen, möchte ich executemany()
von Python MySQL Connector verwenden, so dass ich in Chargen mit einer einzigen Abfrage für jeden Batch aktualisieren kann.Bulk Update MySql mit Python
Antwort
Ich glaube nicht, mysqldb hat eine Art und Weise zu einem Zeitpunkt mehr UPDATE-Abfragen zu verarbeiten.
Sie können jedoch eine INSERT-Abfrage mit ON DUPLICATE KEY UPDATE-Bedingung am Ende verwenden.
Ich schrieb das folgende Beispiel für die Benutzerfreundlichkeit und Lesbarkeit.
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('localhost', 'jeff', 'atwood', 'stackoverflow')
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()
Erklärung der Einzeiler
columns = ', '.join('`{}`'.format(k) for k in data_dict)
ist die gleiche wie
column_list = []
for k in data_dict:
column_list.append(k)
columns = ", ".join(columns)
Hier ist ein Beispiel für die Nutzung
test_data_list = []
test_data_list.append({'id' : 1, 'name' : 'Marco', 'articles' : 1 })
test_data_list.append({'id' : 2, 'name' : 'Keshaw', 'articles' : 8 })
test_data_list.append({'id' : 3, 'name' : 'Wes', 'articles' : 0 })
update_many(data_list=test_data_list, mysql_table='writers')
Abfrage Ausgabe
INSERT INTO writers (`articles`, `id`, `name`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE articles=VALUES(articles), id=VALUES(id), name=VALUES(name)
Werte Ausgang
[[1, 1, 'Marco'], [8, 2, 'Keshaw'], [0, 3, 'Wes']]
Yeah Mysql unterstützt keine Massenaktualisierung. – keshaw
Der obige Code ermöglicht Ihnen das Bulk-Update. –
Vielleicht kann dies helfen How to update multiple rows with single MySQL query in python?
cur.executemany("UPDATE Writers SET Name = %s WHERE Id = %s ",
[("new_value" , "3"),("new_value" , "6")])
conn.commit()
- 1. Bulk-Update in MYSQL
- 2. Mysql Bulk-Update
- 3. Doctrine Bulk DQL-Update mit Join
- 4. Firebase Bulk Update/Delete
- 5. Laravel Bulk UPDATE
- 6. sqlalchemy Bulk-Update Leistungsprobleme
- 7. Magento Bulk-Update-Attribute
- 8. Python MYSQL Update-Anweisung
- 9. effiziente Bulk-Update-Rails-Datenbank
- 10. Python und MySQL UPDATE
- 11. django: Bulk Update-Objekte mit ManyToMany
- 12. Wie man mit Django 'bulk update'?
- 13. Django Bulk-Update mit Zeichenfolge ersetzen
- 14. Bulk-Update in Datenbank mit MLCP
- 15. Bulk Update auf ElasticSearch mit NEST
- 16. Update Bulk-Daten SQL-Server
- 17. Sequelize Bulk Update Array Problem
- 18. Slick 3.0 bulk insert oder update (upsert)
- 19. ElasticSearch Bulk einfügen/Update-Vorgang
- 20. Bulk in MYSQL
- 21. MySQL Query, Bulk-Einfügung
- 22. SQL Bulk-Update, ein Feld Inkrement
- 23. Python Mysql Update Ausführen Befehl
- 24. Bulk einfügen, Update, wenn bei Konflikt (Bulk-Upsert) auf Postgres
- 25. JDBI Ich möchte Bulk-Update mit etwas wie Bulk einfügen mit Objekt erstellen
- 26. Wie Bulk-Aktualisierung von MySQL-Daten mit einer Abfrage?
- 27. Spring Data MongoDB und Bulk-Update
- 28. C# Bulk Insert SqlBulkCopy - Update falls vorhanden
- 29. MySql Bulk-Lade-Befehlszeilen-Tool
- 30. Bulk-Update in SQLAlchemy Core-WHERE
Nizza .. aber ich sehe keine Frage? – Marco
Grundsätzlich möchte ich Executemany für das Update in Python verwenden. Ist es möglich ? – keshaw
Ich denke nicht – Marco