Using Python to Operate Perst
To use Python to operate the Perl database, you need to install the pyperl library. You can install the pyperst library through the pip command:
pip install pyperst
The following is a complete Python code example that shows how to connect to a Perl database and perform data insertion, query, modification, and deletion operations:
python
from pyperst import Database, Field
#Creating Database Objects
db = Database("mydb")
#Define Data Model
class Person(db.Model):
name = Field(str)
age = Field(int)
#Establishing a database connection
db.connect()
#Create a data record
person = Person(name="John", age=25)
#Insert Data Record
person.save()
#Query data
all_people = Person.select()
for person in all_people:
print(person.name, person.age)
#Modify data
person.name = "John Smith"
person.save()
#Delete data
person.delete()
#Close database connection
db.close()
In this code sample, we first create a database object and then define a data model called 'Person', which has two fields called 'name' and 'age'. Next, we establish a database connection using the 'connect()' method. Then a 'Person' object was created and inserted into the database using the 'save()' method. Afterwards, we use the 'select()' method to query all 'Person' records in the database and print each person's name and age. Then we modified a person's name and used the 'save()' method to save the changes. Finally, we deleted this person's record using the 'delete()' method. Finally, we use the 'close()' method to close the database connection.