Using MySQL as a triple store with rdflib/rdfextrasΒΆ

Example code to create a MySQL triple store, add some triples, and serialize the resulting graph.

import rdflib
from rdflib.graph import ConjunctiveGraph as Graph
from rdflib import plugin
from import Store
from import NO_STORE
from import VALID_STORE
from rdflib import Literal
from rdflib import Namespace
from rdflib import URIRef

default_graph_uri = ""
configString = "host=localhost,user=username,password=password,db=rdfstore"

# Get the mysql plugin. You may have to install the python mysql libraries
store = plugin.get('MySQL', Store)('rdfstore')

# Open previously created store, or create it if it doesn't exist yet
rt =,create=False)
if rt == NO_STORE:
    # There is no underlying MySQL infrastructure, create it,create=True)
    assert rt == VALID_STORE,"There underlying store is corrupted"

# There is a store, use it
graph = Graph(store, identifier = URIRef(default_graph_uri))

print("Triples in graph before add: %s" % len(graph))

# Now we'll add some triples to the graph & commit the changes
rdflib = Namespace('')
graph.add((rdflib['pic:1'], rdflib['name'], Literal('Jane & Bob')))
graph.add((rdflib['pic:2'], rdflib['name'], Literal('Squirrel in Tree')))

print("Triples in graph after add: %" % len(graph))

# display the graph in RDF/XML

Previous topic

Using SPARQL to query an rdflib 3 graph

Next topic

Transitive Traversal