This topic describes how to connect to OceanBase AI Database using Django and perform basic database operations, including creating tables, inserting data, updating data, and querying data.
Prerequisites
- You have installed Python 3.x and pip.
- You have installed OceanBase AI Database and created a user tenant.
Procedure
- Obtain the connection string for OceanBase AI Database.
- Install Django and the MySQL client libraries.
- Create a Django project and application.
- Configure the database connection.
- Create models.
- Run migrations.
- Write views and configure URLs.
- Run the development server.
Step 1: Obtain the connection string for OceanBase AI Database
Contact the deployment personnel or administrator of OceanBase AI Database to obtain the corresponding database connection string.
obclient -h$host -P$port -u$user_name -p$password -D$database_name
Parameter description:
$host: The IP address for connecting to OceanBase AI Database. For connections through OceanBase Database Proxy (ODP), use an ODP address; for direct connections, use the IP address of an OBServer node.$port: The port for connecting to OceanBase AI Database. For ODP connections, the default port is2883, which can be customized during ODP deployment. For direct connections, the default port is2881, which can be customized during OceanBase AI Database deployment.$database_name: The name of the database to access.Notice
The user connecting to the tenant must have the
CREATE,INSERT,UPDATE, andSELECTprivileges on this database. For more information about user privileges, see Privilege types.$user_name: The connection account for the tenant. For ODP connections, the common formats areusername@tenant_name#cluster_nameorcluster_name:tenant_name:username. For direct connections, the format isusername@tenant_name.$password: The account password.
For more information about the connection string, see Connect to OceanBase AI Database by using OBClient.
Example:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest
Step 2: Install Django and the MySQL client libraries
Django is an advanced Python web framework that provides an Object-Relational Mapping (ORM) system to simplify database operations. Django supports a variety of database backends, including MySQL, PostgreSQL, and SQLite.
Open the command prompt or PowerShell terminal and run the following commands to install Django and the MySQL client library.
pip install django mysqlclient
After installation, you can verify the installation by running the following command:
pip list | grep -i django
Note
Django is a powerful web framework that provides an ORM system to simplify database operations. Django's ORM system supports a variety of database backends, including MySQL, PostgreSQL, and SQLite.
Step 3: Create a Django project and application
Create a Django project named
oceanbase_demo.django-admin startproject oceanbase_demoNavigate to the project directory.
cd oceanbase_demoCreate an application named
users.python manage.py startapp users
Step 4: Configure the database connection
Open the
oceanbase_demo/settings.pyfile and modify the database configuration.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'test_user001@mysql001', 'PASSWORD': '******', 'HOST': 'xxx.xxx.xxx.xxx', 'PORT': '2881', 'OPTIONS': { 'charset': 'utf8mb4', }, } }Add the
usersapplication toINSTALLED_APPS.INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ]
Step 5: Create models
Open the
users/models.pyfile and create theUsermodel.from django.db import models class User(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() def __str__(self): return f"{self.name} ({self.age})"
Step 6: Run migrations
Create a migration file.
python manage.py makemigrationsPerform application migration.
python manage.py migrate
Step 7: Write view and URL configuration
Open the
users/views.pyfile and create a view function.from django.shortcuts import render from django.http import HttpResponse from .models import User def index(request): # Insert data User.objects.create(name='John', age=20) User.objects.create(name='Lucy', age=25) User.objects.create(name='Tom', age=30) # Update data user = User.objects.get(name='Lucy') user.age = 26 user.save() # Query data users = User.objects.all() result = "<h1>Users</h1><ul>" for user in users: result += f"<li>{user}</li>" result += "</ul>" return HttpResponse(result)Open the
oceanbase_demo/urls.pyfile and configure the URL.from django.contrib import admin from django.urls import path from users import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), ]
Step 8: Run the development server
Run the development server.
python manage.py runserverAccess
http://127.0.0.1:8000/in your browser to view the result.The expected response is as follows:
<h1>Users</h1> <ul> <li>John (20)</li> <li>Lucy (26)</li> <li>Tom (30)</li> </ul>
Error handling
When connecting to OceanBase AI Database using Django, you may encounter various errors. Below are some common errors and their handling methods:
Connection error: If you cannot connect to the database, check whether the connection parameters are correct, including the hostname, port, username, password, and database name.
Permission error: If you encounter a permission-related error, ensure the user has sufficient permissions to perform the required operation.
SQL syntax error: If an SQL statement contains a syntax error, check whether the SQL statement syntax is correct.
Data type error: If the data type of the inserted value does not match the table definition, ensure the inserted data type is correct.
In Django, you can use try-except statements to catch and handle these errors, ensuring the program handles errors gracefully instead of crashing directly. Additionally, you can use Django's logging system to record error information, facilitating debugging and troubleshooting.
References
For more information about connecting to OceanBase AI Database, see Overview of connection methods.
For more information about creating a database, see CREATE DATABASE.