Skip to main content

Connect to seekdb by using Django

This topic describes how to connect to seekdb by using Django and perform basic database operations, including table creation, data insertion, data update, and data query.

Prerequisites

  • You have installed Python 3.x and pip.
  • You have installed seekdb.

Procedure

  1. Obtain the seekdb connection string.
  2. Install Django and the MySQL client library.
  3. Create a Django project and application.
  4. Configure the database connection.
  5. Create a model.
  6. Run migrations.
  7. Write views and URL configurations.
  8. Run the development server.

Step 1: Obtain the seekdb connection string

Contact the seekdb deployment personnel or administrator to obtain the corresponding database connection string.

mysql -h$host -P$port -u$user_name -p$password -D$database_name

Parameter description:

  • $host: the IP address for connecting to seekdb. Replace this parameter with the actual IP address. You can also use the local IP address 127.0.0.1.
  • $port: the port for connecting to seekdb. Replace this parameter with the actual port. The default value is 2881, which can be customized when you deploy seekdb.
  • $database_name: the name of the database to be accessed.
  • $user_name: the username for connecting to seekdb. The format is username.
  • $password: the password for the account.

For more information about the connection string, see Connect to seekdb by using a MySQL client.

Here is an example:

mysql -hxxx.xxx.xxx.xxx -P2881 -uroot -p****** -Dtest

Step 2: Install Django and the MySQL client library

Django is a high-level Python Web framework that provides an ORM (object-relational mapping) system to simplify database operations. Django supports multiple database backends, including MySQL, PostgreSQL, and SQLite.

Open the command prompt or PowerShell terminal and run the following command to install Django and the MySQL client library.

pip install django mysqlclient

After the installation is complete, run the following command to verify whether the installation was successful:

pip list | grep -i django
info

Django is a powerful Web framework that provides an ORM system to simplify database operations. The ORM system of Django supports multiple database backends, including MySQL, PostgreSQL, and SQLite.

Step 3: Create a Django project and application

  1. Create a Django project named seekdb_demo.

    django-admin startproject seekdb_demo
  2. Go to the project directory.

    cd seekdb_demo
  3. Create an application named users.

    python manage.py startapp users

Step 4: Configure the database connection

  1. Open the seekdb_demo/settings.py file and modify the database configuration.

    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'test',
    'USER': 'root',
    'PASSWORD': '******',
    'HOST': 'xxx.xxx.xxx.xxx',
    'PORT': '2881',
    'OPTIONS': {
    'charset': 'utf8mb4',
    },
    }
    }
  2. Add the users application to the INSTALLED_APPS list.

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    ]

Step 5: Create a model

  1. Open the users/models.py file and create a User model.

    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

  1. Create a migration file.

    python manage.py makemigrations
  2. Apply the migration.

    python manage.py migrate

Step 7: Write views and URL configurations

  1. Open the users/views.py file 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)
  2. Open the seekdb_demo/urls.py file 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

  1. Run the development server.

    python manage.py runserver
  2. In the browser, go to http://127.0.0.1:8000/ and view the result.

    The returned result is as follows:

    <h1>Users</h1>
    <ul>
    <li>John (20)</li>
    <li>Lucy (26)</li>
    <li>Tom (30)</li>
    </ul>

Error handling

When you use Django to connect to seekdb, you may encounter various errors. The following are some common errors and their solutions:

  1. Connection error: If you cannot connect to the database, check whether the connection parameters are correct, including the host name, port, username, password, and database name.

  2. Permission error: If you encounter a permission-related error, ensure that the user has sufficient permissions to perform the required operations.

  3. SQL syntax error: If the SQL statement has a syntax error, check whether the syntax of the SQL statement is correct.

  4. Data type error: If the data type of the inserted data does not match the table definition, ensure that the data type of the inserted data is correct.

In Django, you can use the try-except statement to capture and handle these errors, ensuring that the program can handle errors gracefully instead of crashing directly. At the same time, you can use the logging system of Django to record error information for easier debugging and problem troubleshooting.

References