【Python】辞書(ディクショナリ)オブジェクトからインサート文(ON DUPLICATE KEY UPDATE文対応)を生成するクラス
This file contains 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: utf-8 | |
import MySQLdb | |
class MySQL(): | |
def __init__(self, config): | |
connection = MySQLdb.connect(db=config['db'], user=config['user'], passwd=config['passwd'], charset=config['charset'], init_command=config['init_command']) | |
self.cursor = connection.cursor() | |
def insertFromDict(self, table, dict, duplicate_keys=[]): | |
sql = self.buildQueryInsertFromDict(table, dict, duplicate_keys) | |
self.cursor.execute(sql, dict) | |
def dictValuePad(self, key): | |
return "%(" + str(key) + ")s" | |
def keyValuePad(self, key): | |
return key + "=%(" + str(key) + ")s" | |
def buildQueryInsertFromDict(self, table, dict, duplicate_keys): | |
sql = "INSERT INTO " + table + " (" + ",".join(dict) + ") VALUES (" + ",".join(map(self.dictValuePad, dict)) + ")" | |
if len(duplicate_key) > 0: | |
sql += " ON DUPLICATE KEY UPDATE " + ",".join(map(self.keyValuePad, duplicate_keys)) | |
sql += ";" | |
return sql | |
if __name__ == "__main__": | |
mysql = MySQL({ | |
"db": "database", | |
"user": "username", | |
"passwd": "password", | |
"charset": "utf8", | |
"init_command": "set names utf8" | |
}) | |
dict = { | |
"a": "a", | |
"b": "b" | |
} | |
mysql.insertFromDict("table", dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment