Created
August 7, 2018 09:41
-
-
Save lewangdev/014830ce29ddd6d1f6433b05a11c7395 to your computer and use it in GitHub Desktop.
Bulket insert data to MySQL by python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding=utf8 | |
import MySQLdb | |
class Connectdb(): | |
def __init__(self): | |
self._conn = MySQLdb.connect("localhost", "root", "letmein", | |
"db_test", charset="utf8") | |
def __enter__(self): | |
return self._conn | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self._conn.close() | |
def connectdb(): | |
return Connectdb() | |
if __name__ == '__main__': | |
with connectdb() as conn: | |
cursor = conn.cursor() | |
cursor.execute("SELECT VERSION()") | |
data = cursor.fetchone() | |
print("Database version : %s " % data) | |
# Insert data | |
sql = "insert into t_limit(val, source) values(%s, %s)" | |
for j in xrange(50): | |
param = [] | |
for i in xrange(100000): | |
param.append((i, i)) | |
try: | |
cursor.executemany(sql, param) | |
conn.commit() | |
print("batch %s done" % j) | |
except: | |
conn.rollback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment