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類的實例對象執行查詢和非查詢語句。
1.內容有錯還請在評論區指出哦!謝謝!

浙公網安備 33010602011771號