Python Django从安装到云平台攻略(四)数据库调用

Setting.py中
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘tht4’, ##数据库的名称
‘HOST’:’127.0.0.1′, ##数据库主地址
‘PORT’:3306,
‘USER’:’root’,
‘PASSWORD’:’123456′,
}
}
Models.py中:
from django.db import models

Create your models here.

class stn01_info(models.Model):
stn_id = models.IntegerField(primary_key=True)
stn_name = models.CharField(max_length=30)
worker = models.CharField(max_length=30)
stn_x = models.IntegerField()
stn_y = models.IntegerField()
trm01_cap = models.IntegerField()
trm02_cap = models.IntegerField()
def str(self):
return self.ID

Models.py中建立表和字段
from django.db import models
class user_info(models.Model):
ID = models.IntegerField(primary_key=True)
user_name = models.CharField(max_length=30)
user_key = models.CharField(max_length=30)

注意!不要在最后写:
def str(self):
return self.ID

然后通过
python manage.py makemigrations
python manage.py migrate
将表和字段设计同步到mysql数据库中
然后通过mysql——workbench,在表中添加多条记录
在要使用记录数据的python文件中中
from app01.models import user_info
user01 = user_info.objects.get(user_name=’kdkj’)

数据库外键约束的暂时忽略:
问题:在执行python manage.py migrate时,出现:
django.db.utils.OperationalError: (1833, “Cannot change column ‘ID’: used in a foreign key constraint ‘app01_wcu_data_01_dvc_id_id_7ac564ae_fk_app01_wc u_tag_ID’ of table ‘fyy01.app01_wcu_data_01′”)
则在settings文件中添加数据库设置
DATABASES = {
‘default’: {
‘OPTIONS’: { “init_command”: “SET foreign_key_checks = 0;”, }
}
}
在开发完成之后可以把该设置去掉

temp = user_info.objects.get(user_name=’kdkj’)
user01 = temp.qx_pro.split(‘,’) ##先把字符串转换为数组
user01 = list(map(int,user01)) ##再把字符数组转换为整形数组

import pymysql
data_db = pymysql.connect(host=’localhost’,
port=3306,
user=’root’,
passwd=’123456′,
db=’kd’)

创建游标

cursor = data_db.cursor()

查询

try:
sql = “select * from app01_data_smp”
cursor.execute(sql)
row_num = cursor.rowcount # 查询一共有多少条数据
data_store = cursor.fetchall()
dt_id = data_store[row_num – 1][0]
print(dt_id)
except:
print(“error”)

for i in range(10):
dt_id = dt_id + 1
sql = “INSERT INTO kd. app01_data_smp (dt_ID, date_ic, time_ic, dt_dir, dt_type, dt_value, sensor_id) VALUES (%s,%s,%s,%s,%s,%s,%s)”
nowtime = datetime.datetime.now()
date_ic = int(“%04d” % nowtime.year + “%02d” % nowtime.month + “%02d” % nowtime.day)
time_ic = int(“%02d” % nowtime.hour + “%02d” % nowtime.minute + “%02d” % nowtime.second)
dt_dir = 1
dt_type = 19
dt_value = random.randint(60, 80)
sensor_id = 1001010205
cursor.execute(sql, [dt_id, date_ic, time_ic, dt_dir, dt_type, dt_value, sensor_id])
time.sleep(0.05)

提交,不然无法保存新建或者修改的数据

data_db.commit()

关闭游标

cursor.close()

关闭连接

data_db.close()

Original: https://blog.csdn.net/tsatnt/article/details/122271853
Author: tsatnt
Title: Python Django从安装到云平台攻略(四)数据库调用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/736364/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球