0

在此示例中,我尝试添加一个新的作者节点,该节点从密码代码外部获取变量。这种方法适用于普通的 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()
4

2 回答 2

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))

两项工作都适合我。

于 2019-02-07T08:27:07.653 回答
0

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

        name = 'Apel'
        firstName = 'Jan'
        lastName = 'Apel'
        initials = ''
        cypher = "CREATE (n:Author { name:  \'"   + name + "\', firstName: \'" + firstName + "\', lastName: \'" + lastName + "\', initials: \'" + initials + "\' })"
        cur.execute(cypher)
于 2018-10-29T14:16:40.587 回答