使用python在neo4j中传递参数

2024-06-28 23:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python在CREATE中传递参数 例如: '''

n = "abc"
a = 1234

cqlCreate = "CREATE (cornell:university { name: $n,yob:$a})"

'''

但是它不起作用。。有什么建议吗


Tags: name参数create建议abcuniversitycornellyob
2条回答

可以在Python中使用f字符串。见下面的例子。注意

  1. You need to use {{ as escape character for {

2 You need to use \ as escape character for "

n = "abc"
a = 1234

cqlCreate = f"CREATE (cornell:university {{name: \"{n}\", yob: {a}}})"
print (cqlCreate)

Result:
CREATE (cornell:university {name: "abc", yob: 1234})

参考:https://www.python.org/dev/peps/pep-0498/

它实际上取决于您用来连接Neo4j的Python驱动程序(请检查https://neo4j.com/developer/python/以查看可用驱动程序的列表)。如果您使用的是官方的neo4j驱动程序,那么您编写的代码是正确的。为了执行密码查询,您可以执行以下操作:

from neo4j import GraphDatabase

uri = # insert neo4j uri
user = # insert neo4j username
password = # insert neo4j password

n = "abc"
a = 1234
query = "CREATE (cornell:university { name: $n,yob:$a})"

driver = GraphDatabase.driver(uri, auth=(user, password))
session = driver.session()
result = session.run(query, n=n, a=a)
session.close()
driver.close()

虽然–ōŏŷXmoůŜ的答案可能会奏效,但不建议采用这种方法

另见

相关问题 更多 >