How to use Python to operate CrateDB
To operate CrateDB using Python, you need to install the Crate package and the Crate. client package. You can install craft and craft. client using the following command:
pip install crate
pip install crate.client
After installing the dependency library, you can use the following code example to implement data addition, deletion, modification, and query operations:
python
from crate import client
#Connect to CrateDB
connection = client.connect('localhost:4200')
#Create a table (if it does not exist)
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name STRING)")
#Insert Data
with connection.cursor() as cursor:
cursor.execute("INSERT INTO users (id, name) VALUES (?, ?)", (1, "John Doe"))
cursor.execute("INSERT INTO users (id, name) VALUES (?, ?)", (2, "Jane Smith"))
#Query data
with connection.cursor() as cursor:
cursor.execute("SELECT id, name FROM users")
result = cursor.fetchall()
for row in result:
print(row)
#Update data
with connection.cursor() as cursor:
cursor.execute("UPDATE users SET name = ? WHERE id = ?", ("John Wick", 1))
#Delete data
with connection.cursor() as cursor:
cursor.execute("DELETE FROM users WHERE id = ?", (2,))
#Close Connection
connection.close()
In the above code example, first connect to CrateDB and then create a table named "users" (if it does not exist). Next, we will insert the records of two users. Then query all the data in the table and print it out. Next, we update the name of the user with id 1 and delete the record of the user with id 2. Finally, we closed the connection to CrateDB.
This is a simple example that you can fine-tune and expand according to your actual needs and table structure.