rdflib图未更新。为什么?

2 投票
1 回答
778 浏览
提问于 2025-04-15 16:45

我正在试图理解这种行为。这绝对不是我所期待的结果。我有两个程序,一个是读取程序,一个是写入程序。读取程序打开了一个RDFlib图形存储,然后每两秒进行一次查询。

import rdflib
import random
from rdflib import store
import time

default_graph_uri = "urn:uuid:a19f9b78-cc43-4866-b9a1-4b009fe91f52"

s = rdflib.plugin.get('MySQL', store.Store)('rdfstore')

config_string = "host=localhost,password=foo,user=foo,db=foo"
rt = s.open(config_string,create=False)
if rt != store.VALID_STORE:
    s.open(config_string,create=True)


while True:
    graph = rdflib.ConjunctiveGraph(s, identifier = rdflib.URIRef(default_graph_uri))
    rows = graph.query("SELECT ?id ?value { ?id <http://localhost#ha> ?value . }")
    for r in rows:
        print r[0], r[1]
    time.sleep(2)
    print " - - - - - - - - "

第二个程序是写入程序,它往三元组存储中添加内容。

import rdflib
import random
from rdflib import store

default_graph_uri = "urn:uuid:a19f9b78-cc43-4866-b9a1-4b009fe91f52"

s = rdflib.plugin.get('MySQL', store.Store)('rdfstore')

config_string = "host=localhost,password=foo,user=foo,db=foo"
rt = s.open(config_string,create=False)
if rt != store.VALID_STORE:
    s.open(config_string,create=True)

graph = rdflib.ConjunctiveGraph(s, identifier = rdflib.URIRef(default_graph_uri))

graph.add( ( 
            rdflib.URIRef("http://localhost/"+str(random.randint(0,100))), 
            rdflib.URIRef("http://localhost#ha"),
            rdflib.Literal(str(random.randint(0,100)))
            ) 
            )
graph.commit()

我本以为当我用写入程序提交内容时,读取程序的结果数量会增加,但实际上并没有发生这种情况。读取程序继续返回启动时的结果。如果我停止读取程序并重新启动它,新结果就会出现。

有没有人知道我哪里做错了?

1 个回答

3

一个简单的解决办法是在“graph = rdflib.ConjunctiveGraph(...)”这一行后面加上“graph.commit()”。我不太确定原因是什么,为什么在读取之前提交会解决这个问题。我在这里猜测:

  • 当打开 MySQLdb 连接时,会自动开始一个事务。
  • 这个事务看不到其他后续事务的更新。
  • “graph.commit()”实际上会触发某个地方的“connection.commit()”,这样就会放弃当前的事务并开始一个新的事务。

撰写回答