从NSDictionary生成SQL查询

从NSDictionary生成SQL查询,sql,swift,swift3,Sql,Swift,Swift3,我想从Dictionary对象生成SQL语句。因为我必须消除相应列中空字符串的更新过程。我可以通过Swift代码来完成这项工作,但重复这样做并不好。有没有办法通过SQL语句实现这一点 我在StackOverflow上找到了一些链接。 及 类似于python代码中的示例 def insertFromDict(table, dict): """Take dictionary object dict and produce sql for inserting it into the

我想从Dictionary对象生成SQL语句。因为我必须消除相应列中空字符串的更新过程。我可以通过Swift代码来完成这项工作,但重复这样做并不好。有没有办法通过SQL语句实现这一点

我在StackOverflow上找到了一些链接。

类似于python代码中的示例

def insertFromDict(table, dict):
    """Take dictionary object dict and produce sql for 
    inserting it into the named table"""
    sql = 'INSERT INTO ' + table
    sql += ' ('
    sql += ', '.join(dict)
    sql += ') VALUES ('
    sql += ', '.join(map(dictValuePad, dict))
    sql += ');'
    return sql

def dictValuePad(key):
    return '%(' + str(key) + ')s'
所需功能:

func sqlFrom(dict : [String : String], for table : String) -> String {
    let keys = dict.keys.joined(separator: ", ")
    var values = dict.values.joined(separator: "', '")
    values = """
    '\(values)'
    """
    let sql = "INSERT INTO \(table) ( \(keys) ) VALUES ( \( values) );"
    return sql
}
检查结果:

所需功能:

func sqlFrom(dict : [String : String], for table : String) -> String {
    let keys = dict.keys.joined(separator: ", ")
    var values = dict.values.joined(separator: "', '")
    values = """
    '\(values)'
    """
    let sql = "INSERT INTO \(table) ( \(keys) ) VALUES ( \( values) );"
    return sql
}

检查结果:

以下方法将完成此任务,但不会阻止sql注入

func insertStatement(table: String, dict: [String : Any]) -> String {
    let values: [String] = dict.values.compactMap { value in
        if value is String || value is Int || value is Double {
            return "'\(value)'"
        } else if let date = value as? Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return "'" + dateFormatter.string(from: date) + "'"
        }
        // handle other types if necessary

        return nil
    }

    return "INSERT INTO \(table) (" + dict.keys.joined(separator: ",") + ") VALUES (" + values.joined(separator: ",") + ")"
}
用法:
insertStatement(表:“测试表”,目录:[“id”:8,“name”:“John”,“age”:Date())

输出:
将值('8'、'2019-04-24'、'John')插入测试表(id、年龄、姓名)

为了防止SQL注入,您必须使用准备好的语句来绑定值,例如在PHP的PDO库中,如下所示:

func insertStatement(table: String, dict: [String : Any]) {
    let columns = dict.keys.joined(separator: ",")
    let values = dict.keys.map({ ":" + $0 }).joined(separator: ",")

    // build the statement
    let sql = "INSERT INTO " + table + "(" + columns + ") VALUES (" + values + ")"

    var bind: [String : Any] = [:]
    for (column, value) in dict {
        bind[":\(column)"] = value
    }
}

下面的方法将完成这项工作,但不会阻止sql注入

func insertStatement(table: String, dict: [String : Any]) -> String {
    let values: [String] = dict.values.compactMap { value in
        if value is String || value is Int || value is Double {
            return "'\(value)'"
        } else if let date = value as? Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return "'" + dateFormatter.string(from: date) + "'"
        }
        // handle other types if necessary

        return nil
    }

    return "INSERT INTO \(table) (" + dict.keys.joined(separator: ",") + ") VALUES (" + values.joined(separator: ",") + ")"
}
用法:
insertStatement(表:“测试表”,目录:[“id”:8,“name”:“John”,“age”:Date())

输出:
将值('8'、'2019-04-24'、'John')插入测试表(id、年龄、姓名)

为了防止SQL注入,您必须使用准备好的语句来绑定值,例如在PHP的PDO库中,如下所示:

func insertStatement(table: String, dict: [String : Any]) {
    let columns = dict.keys.joined(separator: ",")
    let values = dict.keys.map({ ":" + $0 }).joined(separator: ",")

    // build the statement
    let sql = "INSERT INTO " + table + "(" + columns + ") VALUES (" + values + ")"

    var bind: [String : Any] = [:]
    for (column, value) in dict {
        bind[":\(column)"] = value
    }
}