将字典作为参数传递给函数以执行查询

时间:2018-04-06 11:09:45

标签: database python-3.x

我有一个名为database的类,它实现了curd功能。我想传递一个字典作为参数插入一个函数来执行查询。

        import pymysql as my
        class Database(object):
            def __init__(self):
                self.user = 'root'
                self.host = '127.0.0.1'
                self.pwd = ''
                self.db = 'premonition'

                try:
                    self.dbs = my.connect(self.host,self.user,self.pwd,self.db)
                    self.cursor = self.dbs.cursor()
                    print(self.cursor.execute('select version()'))

                except my.Error as error:
                    print ('Error: %s ' %error + '\nStop.\n')

           def insertRow(self,*args,**kwargs):

            sql = "insert into {1} {2}            
            values{3}".format(args,str(kwargs.keys(),str(kwargs.values()))
            try:
                self.cursor.execute(sql)
                self.dbs.commit()
            except Exception as e:
                print("Error during insert:::",e)
db = Database()
db.insertRow(tablename = "test", data ={'roll_id':'251452', 'name': 'Python', 'age': 28})

如何执行查询我得到的是错误。

File "database.py", line 72, in <module>    
db.insertRow(tablename = "test", data ={'roll_id':'251452', 'name': 'Python', 'age': 28})
File "database.py", line 25, in insertRow    
sql = "insert into {1} {2} values {3}".format(args,str(kwargs.keys(),str(kwargs.values())))
TypeError: coercing to str: need a bytes-like object, dict_keys found

1 个答案:

答案 0 :(得分:0)

我不知道是单独调用keys()和values()总是得到正确的pair key:value,所以可以这样做,以确保它

template = "insert into {0} {1} values{2}"
keys = []
values = []

for k,v in d.items():
    keys.append(str(k))
    values.append(str(v))

sql = template.format(some_name, tuple(keys), tuple(values)

以其他方式可能只是这个

template.format(some_name, tuple(kwargs.keys()), tuple(kwargs.values())

如果您想使用唯一的表名,也可以根据需要使用args变量。也许你必须重新考虑这段代码。