Using Python to Operate OrientDB
To use Python to operate OrientDB database connections and data operations, we can use the Copyright library. Copyright is a Python driver used to interact with OrientDB. To install the copy library, you can use the pip command to install:
pip install pyorient
The following is a complete Python code example that demonstrates how to connect to an OrientDB database and how to insert, query, modify, and delete data:
python
import pyorient
#Connect to OrientDB database
client = pyorient.OrientDB("localhost", 2424)
session_id = client.connect("root", "root")
#Open an existing database or create a new one
db_name = "test"
username = "admin"
password = "admin"
if client.db_exists(db_name, pyorient.STORAGE_TYPE_MEMORY):
client.db_open(db_name, username, password)
else:
client.db_create(db_name, pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY)
client.db_open(db_name, username, password)
#Insert Data
data = {'name': 'John', 'age': 30}
record = client.record_create().set_o_class('Person').set_o_document(data)
client.record_save(record)
#Query data
query = "SELECT * FROM Person WHERE name = 'John'"
result = client.command(query)
for record in result:
print(record.oRecordData)
#Modify data
record.oRecordData['age'] = 31
client.record_save(record)
#Delete data
client.record_delete(record._rid)
#Close Connection
client.db_close()
The above code first connects to the OrientDB database using a username and password. Then, it opens an existing database or creates a new one. Next, it inserts a piece of data and uses a query to retrieve it and print it out. Then, it modifies the age field of the data and saves the updated record. Finally, it deletes the record and closes the connection to the database.
Please note that the above code assumes that the OrientDB server is running on port 2424 on the local host and uses the default root username and password on the server. You can make corresponding modifications based on your actual settings.