通过Python和cypher在Agensgraph中插入节点

时间:2018-10-29 13:47:31

标签: python cypher agens-graph

在此示例中,我尝试添加一个新的author节点,该节点从密码代码外部获取变量。这种方法适用于普通的PostgreSQL代码,但是我正在尝试正确使用语法以允许python为我做。我已经导入了pyscopg2和agensgraph。如果属性是手动添加的,则代码可以正常工作。以下代码返回错误:

'str'对象不可调用

    def newAuthor(self):
    self.statusBar().showMessage('Processing...')
    try:
        # connect to the PostgreSQL server
        conn = psycopg2.connect("dbname=agens host=localhost user=agens password=pw port=5433")
        cur = conn.cursor()

        cur.execute("""SET graph_path = publications;""")


        name = 'Apel'
        firstName = 'Jan'
        lastName = 'Apel'
        initials = ''

        cur.execute("""
        CREATE (n:Author { name: %s, firstName: %s, lastName: %s, initials: %s })
        """(name, firstName, lastName, initials))


        cur.close()
        conn.commit()
        self.statusBar().showMessage('Ready')
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        conn.close()

2 个答案:

答案 0 :(得分:1)

我知道这是一个很晚的答案,您可以自己找到答案。

只想分享我在python中使用密码查询的方式。希望这可能对将来的人有所帮助。

如果您不介意将参数与其顺序绑定,则可以使用以下方式:

createCypher = "CREATE (n:Author {name : %s, firstName : %s, lastName : %s, initials : %s })"
name = "Apel"
firstName = "Jan"
lastName = "Apel"
initials = ""
cur.execute (createCypher, (name, firstName, lastName, initials, ))

但是,如果您想用听写键指定参数的位置,我相信用格式构建查询字符串是唯一的方法:

createCypher = "CREATE (n:SUBJECT {{name :'{name}', firstName: '{firstName}', lastName : '{lastName}', initials : '{initials}' }})"
param = {}
param["name"] = "Apel2"
param["firstName"] = "Jan2"
param["lastName"] = "Apel2"
param["initials"] = ""
cur.execute(createCypher2.format(**param))

两个工作都找到我。

答案 1 :(得分:0)

这解决了问题,这是最好的方法吗?

        name = 'Apel'
        firstName = 'Jan'
        lastName = 'Apel'
        initials = ''
        cypher = "CREATE (n:Author { name:  \'"   + name + "\', firstName: \'" + firstName + "\', lastName: \'" + lastName + "\', initials: \'" + initials + "\' })"
        cur.execute(cypher)