Using a Python dict for a SQL INSERT statement

前端 未结 10 1351
小蘑菇
小蘑菇 2020-11-28 22:43

I am trying to use a dict to do a SQL INSERT. The logic would basically be:

INSERT INTO table (dict.keys()) VALUES dict.values()
         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 22:58

    I tried @furicle's solution but it still inputs everything as a string - if your dict is a mixed one then this may not work as you would want it to. I had a similar issue and this is what I came up with - this is only a query builder and you could use it (with changes) to work with any database of your choice. Have a look!

    def ins_query_maker(tablename, rowdict):
        keys = tuple(rowdict)
        dictsize = len(rowdict)
        sql = ''
        for i in range(dictsize) :
            if(type(rowdict[keys[i]]).__name__ == 'str'):
                sql += '\'' + str(rowdict[keys[i]]) + '\''
            else:
                sql += str(rowdict[keys[i]])
            if(i< dictsize-1):
                sql += ', '
        query = "insert into " + str(tablename) + " " + str(keys) + " values (" + sql + ")"
        print(query) # for demo purposes we do this
        return(query) #in real code we do this
    

    This is crude and still needs sanity checks, etc, but it works as intended. for a dict:

    tab = {'idnumber': 1, 'fname': 'some', 'lname': 'dude', 'dob': '15/08/1947', 'mobile': 5550000914, 'age' : 70.4}
    

    running the query I get the following output

    results of query generated by the suite

提交回复
热议问题