django连接已有数据的mysql数据库

django连接已有数据的mysql数据库

django==2.1.8

mysql==5.7

案例一:

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': BASE_DIR / 'db.sqlite3',
        "ENGINE": "django.db.backends.mysql",  # mysql配置
        "OPTIONS": {
            'charset': 'utf8mb4',
            'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
        },
        "HOST": DATABASE_HOST,
        "PORT": DATABASE_PORT,
        "USER": DATABASE_USER,
        "PASSWORD": DATABASE_PASSWORD,
        "NAME": DATABASE_NAME,
    },
    'mysql_cexun': {  # 新增的已有数据的数据库
        "ENGINE": "django.db.backends.mysql",  # mysql配置
        "HOST": consts.DATABASE_HOST_CEXUN,
        "PORT": consts.DATABASE_PORT_CEXUN,
        "USER": consts.DATABASE_USER_CEXUN,
        "PASSWORD": consts.DATABASE_PASSWORD_CEXUN,
        "NAME": consts.DATABASE_NAME_CEXUN,
    }
}

保证配置是正确的,数据库访问不报错,进入下一步,生成models模型

python manage.py inspectdb --database  mysql_cexun  # 指定生成数据库所有表的模型
# 或
python manage.py inspectdb --database  mysql_cexun  user # 指定生成数据库user表的模型
# 或
python manage.py inspectdb --database  mysql_cexun  user > models.py # 指定生成user表的模型在models.py文件中

这个时候会出现下面的显示

PS F:\Project\Flexible_platform_server> python manage.py inspectdb --database  mysql_cexun table user
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
# Unable to inspect table 'table'
# The error was: (1146, "Table 'vtehil.table' doesn't exist")


class User(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    name = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user

这是我们就将模型添加到已有或新的models.py中使用即可,使用注意指定数据库

class User(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    name = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False  # 这里是False,代表不创建新的表,使用已存在的表
        db_table = 'user'  # 指定已存在的表名

在上述代码中,我们通过继承models.Model来定义一个模型类,并在类中定义各个字段对应数据库表中的列。由于我们要连接的是已经存在的表,因此需要设置managed=False来禁止Django创建新的表,并通过db_table属性指定已存在的表名。

使用的时候注意,在orm语句中要用using()属性指定使用的数据库连接。

usersdept_all = models.VtehilCarTestpower.objects.using("mysql_cexun").last()
        print("UsersDept---", usersdept_all.ftarget_c)

案例二:

不用setting中的配置,自己写MySQL连接的模块去使用。

在Python中,可以使用第三方模块mysql-connector-python来连接MySQL数据库。以下是一个简单的MySQL连接模块示例,具体的实现需要根据具体的应用场景进行完善和扩展。

mysql连接模块案例一:

import mysql.connector

class MySQLConnector:
    def __init__(self, host, port, user, password, database):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.conn = None

    def connect(self):
        if self.conn is None or not self.conn.is_connected():
            self.conn = mysql.connector.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database
            )

    def query(self, sql):
        if self.conn is None or not self.conn.is_connected():
            self.connect()
        cursor = self.conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        return result

    def execute(self, sql):
        if self.conn is None or not self.conn.is_connected():
            self.connect()
        cursor = self.conn.cursor()
        cursor.execute(sql)
        self.conn.commit()
        cursor.close()

    def __del__(self):
        if self.conn is not None and self.conn.is_connected():
            self.conn.close()

mysql连接模块案例二:

import mysql.connector

class MySQL:
    def __init__(self, host, port, user, password, database):
        self.conn = mysql.connector.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            auth_plugin='mysql_native_password'  # 可选参数,用于解决5.7版本以上的认证问题
        )
        self.cursor = self.conn.cursor()

    def query(self, sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result

    def execute(self, sql):
        self.cursor.execute(sql)
        self.conn.commit()

    def __del__(self):
        self.cursor.close()
        self.conn.close()

以上代码将MySQL连接封装为一个类MySQLConnector,在类的构造函数中初始化连接所需的主机地址、端口、用户名、密码和要连接的数据库名。类中定义了一个connect()方法,用于在需要时建立连接。query()execute()方法分别用于执行查询和非查询语句。

在类的析构函数中,释放资源。注意,在使用时应该手动调用__del__()方法释放资源,防止资源泄露。

在以后的Python项目中使用该模块时,只需要将该模块导入到项目中,然后实例化MySQLConnector对象并调用其方法即可。例如:

from myapp.mysql_connector import MySQLConnector

connector = MySQLConnector('localhost', 3306, 'user', 'password', 'database')
results = connector.query('SELECT * FROM my_table')
# do something with the query results
connector.execute('UPDATE my_table SET field=value WHERE id=1')
# ...

以上代码演示了在Python程序中如何使用MySQLConnector类的实例对象执行查询和非查询语句。

posted @ 2023-04-27 02:23  只有时间是永恒  阅读(508)  评论(0编辑  收藏  举报