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

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

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)) ##再把字符数组转换为整形数组

利用pymysql *** 作数据库

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()

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5689748.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存