python使用pygraphdb连接graphdb图数据库

python使用pygraphdb连接graphdb图数据库,第1张

python使用pygraphdb连接graphdb图数据库

文章目录
  • 前言
  • 一、GraphDB是什么?
  • 二、使用pygraphdb连接graphdb
    • 1.安装pygraphdb
    • 2. 使用
    • 3. 进阶使用(使用with)

前言

本文主要介绍如何用python *** 作graphdb,以及相应包pygraphdb的安装和使用

一、GraphDB是什么?

GraphDB 是一个高效、强大的图形数据库, 支持RDF和SPARQL。
通过使用SPARQL语句查询数据。

二、使用pygraphdb连接graphdb 1.安装pygraphdb

pip install pygraphdb

2. 使用
import pygraph

# 数据库 config
host = '0.0.0.0'
port = '7200'
db = 'db_name'
user = 'admin'
password = 'password'

# sparql 语句
sparql = 'PREFIX pub:  ' 
    'PREFIX pub-old:  ' 
    'select distinct ?x ?Person  ' 
    'where {?x a pub:Person . ' 
    '?x pub:preferredLabel ?Person . ' 
    '?doc pub-old:containsMention / pub-old:hasInstance ?x .}'

# 连接数据库
db = pygraph.connect(host, port, db, user, password)

# 获取 cursor
cur = db.cursor()

# 执行sparql语句,得到结果
result = cur.execute(sparql)
print(result)

# 关闭 cursor
cur.close()

# 关闭数据库
db.close()

3. 进阶使用(使用with)
# 第一种方式

with pygraph.connect(host, port, db, user, password) as db2:
    # 获取 cursor
    cur2 = db2.cursor()
    # 执行sparql语句,得到结果
    result2 = cur2.execute(sparql)
    cur2.close()
    print(result2)


# 第二种方式

db3 = pygraph.connect(host, port, db, user, password)

# 获取 cursor
with db3.cursor() as cur3:
    # 执行sparql语句,得到结果
    result3 = cur3.execute(sparql)
    print(result3)

db3.close()

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5579593.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存