Python与MySQL之数据写入

之前一直都知道数据库,但从来没有着手尝试过,这次终于实际操作了一下,简单了解了数据库的数据存储。

首先进行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()

、初始化相关参数很重要,确保数据写入制定位置,同时与数据库开辟的类型相符

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangxiaobei2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值