Swift Neo4j如何在Cypher Query中将变量放入引号?

时间:2018-01-16 11:32:52

标签: swift neo4j cypher

这是我的Swift Xcode项目中的代码:

@IBAction func runCypherTapped(_ sender: UIButton) {

        clientName = clientNameField.text

        guard let theo = self.theo else {
            log("Client not initialized yet")
            return
        }

        let result = theo.executeCypherSync("MATCH (c:Client) WHERE c.name = \(clientName) RETURN c.name as name, c.dob as dateOfBirth")
        switch result {
        case let .failure(error):
            log("Error while getting cypher results: \(error)")
        case let .success(queryResult):
            if let arrayClients = queryResult.rows[21]["name"] as? String {
                log("Asked via Cypher how many nodes there are with label 'name'. Answer: \(arrayClients)")

                query.append(arrayClients)
                print(query)
            } else {
                log("Got unexpected answer back")

我想将我的字符串变量clientName放入查询但在引号内,Neo4j需要您想要检索的属性周围的引号,例如:

MATCH (c:Client) WHERE c.name = "Mr Smith"  RETURN c.name as name

考虑到这一点,我尝试了插值并且还逃避了角色,但没有任何成功。我需要上面的查询才能打印出来,但是"史密斯先生"而是由我的clientName字符串变量定义。

仅供参考我在打印到控制台时得到这个:

WHERE c.name = \"Optional(\"Mr Smith\")\" RETURN c.name as name

你可以看到它放置了第一个引号,但不是史密斯之后的第二个引号。

1 个答案:

答案 0 :(得分:1)

Cypher查询中无需硬编码引号。您应该将clientName作为字符串parameter传递,这也可以提高您的查询效率和安全性:

let params: [String:PackProtocol] = ["clientName": clientName]
let result = theo.executeCypherSync(
  "MATCH (c:Client) WHERE c.name = $clientName RETURN c.name as name, c.dob as dateOfBirth",
  params: params)