1

如何找出一个类是否存在;这允许防止“当前数据库中已存在类 x”错误消息?

我看过下面的Question,它用 Java 和 SQL 给出了答案。我正在寻找 Python 等价物。

4

2 回答 2

0

我在以下示例中创建了pyorient

我的结构:

在此处输入图像描述

PyORIENT 代码:

import pyorient

db_name = 'Stack37277880'

print("Connecting to the server...")
client = pyorient.OrientDB("localhost",2424)
session_id = client.connect("root","root")
print("OK - sessionID: ",session_id,"\n")

if client.db_exists( db_name, pyorient.STORAGE_TYPE_PLOCAL ):
    client.db_open(db_name, "root", "root")
    dbClasses = client.command("SELECT name FROM (SELECT expand(classes) FROM metadata:schema)")
    newClass = "MyClass"
    classFound = False
    for idx, val in enumerate(dbClasses):
        if (val.name == newClass):
            classFound = True
            break
    if (classFound != True):
        client.command("CREATE CLASS " + newClass)
        print("Class " + newClass + " correctly created")
    else:
        print("Class " + newClass + " already exists into the DB")

client.db_close() 

首次运行输出:

Connecting to the server...
OK - sessionID:  70 

Class MyClass correctly created

东方数据库工作室:

在此处输入图像描述

第二次运行输出:

Connecting to the server...
OK - sessionID:  74 

Class MyClass already exists into the DB

希望能帮助到你

于 2016-05-17T15:59:18.367 回答
-1

您可以使用与 Java 示例中相同的查询。

import pyorient

className = "MyClass"

database = pyorient.OrientDB("localhost", 2424)
database.db_open(
"DB_name",
"user",
"password"
)

if not database.command("SELECT FROM ( SELECT expand( classes ) FROM metadata:schema ) WHERE name = '%s'" % className):
    print("Create class %s" % className)
    database.command("CREATE CLASS %s EXTENDS V" % className)
else:
    print("Class already exist.")
于 2016-12-07T20:34:06.707 回答