之前一直都知道数据库,但从来没有着手尝试过,这次终于实际操作了一下,简单了解了数据库的数据存储。
首先进行MySQL下载
安装后入下图所示,其中只用到两个,一个命令行:用sql语句创建数据库的表,一个是数据库GUI
在命令行输入sql语句进行数据库的创建 database 和 table
drop database if exists LCFD_sql;
create database LCFD_sql default charset utf8;
use LCFD_sql;
drop table if exists LCFD_table;
create table LCFD_table
(
dTime datetime not null comment '时间',
dElectric int not null comment '电流',
dDistance int not null comment '距离',
dWarning int not null comment '报警'
);
import pymysql (anaconda 下默认安装了pymysql)
# 数据库参数初始化
def MysqlInit():
global LiSQL
# 1. 创建数据库连接对象
LiuCaoSQL = pymysql.connect(host=filejson['MysqlInit']['host'], port=filejson['MysqlInit']['port'],
database=filejson['MysqlInit']['database'], charset=filejson['MysqlInit']['charset'],
user=filejson['MysqlInit']['user'], password=filejson['MysqlInit']['password'])
def WriteToMysql(CurrentTime, Distance, WaringStatus):
# 创建游标
cursor = LiuCaoSQL.cursor()
# 3. 通过游标执行SQL并获得执行结果 执行SQL,并返回收影响行数
result = cursor.execute('insert into lcfd_table values (%s, %s, %s)',(CurrentTime, Distance, WaringStatus))
if result == 1:
print('添加成功!')
else:
print('添加数据失败!')
# 4. 操作成功提交事务
LiuCaoSQL.commit()
# 关闭游标
cursor.close()
# 关闭数据库
def CloseMysql():
# 关闭连接
LiuCaoSQL.close()
、初始化相关参数很重要,确保数据写入制定位置,同时与数据库开辟的类型相符