使用python将数据插入db

时间:2017-01-21 04:36:35

标签: python mysql json

我使用python web服务器将数据插入表中。我能够发送信息以使用ajax调用插入

{
  "verb":"addPerson",
  "person":{
            "name":"what this",
            "email":"whatis@gmail"
  }
}

def addPerson(model, request):
    person = request["person"]
    print person
    return database.insertObj(person, "users")

打印人员将打印此

{u'name': u'what this', u'email': u'whatis@gmail'}

def insertObj(obj, tableName):

    d = dict(obj)  

    # Write SQL Query
    query = "INSERT INTO {0} ({1}) VALUES ({2})"
    columns = ','.join(d.keys())
    placeholders = ','.join(['"%s"'] * len(d))
    sql = query.format(tableName, columns, placeholders) % tuple(d.values())

    # Run It and Handle Error
    dbResponse = executeSQL(sql)

    if ("error" in dbResponse) : return dbResponse

    else :
        cursor = dbResponse["cursor"]
        response = {"newId": cursor.lastrowid}
        cursor.close() 
        config.conn.commit()
        return response

但是当我在python中创建自己的对象时,它会返回一个mysql错误

def test(model, request):
    fromUser = request['username']
    toUser = request["name"]
    fromQuery = "SELECT * FROM users where name='{}' LIMIT 1".format(fromUser)
    toQuery = "SELECT * FROM users where name='{}' LIMIT 1".format(toUser)
    logRequest = {
        'from':str(fromUser),
        'too_number':str(database.get_row(toQuery)['telephone']),
        'too':str(toUser),
        'from_number':str(database.get_row(fromQuery)['telephone']),
        'time':str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')),
        'responded':'false'
    }
    print logRequest
    print database.insertObj(logRequest, "requests")

继承人的回报

  

{'错误':' MySQL错误:1064(42000):您的SQL中有错误   句法;查看与MySQL服务器版本对应的手册   正确的语法使用在“' from,too,too,too_number,response)附近   价值观("私人数据","道森斯宾塞","道斯\'第1行'}

我在logRequest中的错误是什么?如果是这样我将如何解决这个问题?

0 个答案:

没有答案