树莓派与服务器的简单通信

树莓派与服务器的简单通信,第1张

树莓派与服务器的简单通信

话不多说,直接上代码:

import pymysql
import time
# 打开数据库连接
def source_check(name_str):
    db = pymysql.connect(
        host='',#填入你的服务器公网地址
        port=,#填入你的服务器的端口
        user='',#填入你的数据库的用户名
        passwd='',#填入你的数据库的密码
        db='',#填入你的数据库里面想要 *** 作的表
        charset='utf8'
    )
    print("数据库开启")
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    sql1 = 'insert into test3(name,genDate,expDate) (select name,genDate,expDate from test2 as f where f.name = %s)'
    sql2="delete from test2 where name=%s"
    try:
        # 执行sql语句
        cursor.execute(sql1, (name_str))
        #cursor.execute(sql2,(name_str))
        # 提交到数据库执行
        db.commit()
        print("success!")
    except:
        db.rollback()
        print("fail!")
    cursor.close()
    db.close()
    print("程序结束n")
name_str='鸡蛋'
source_check(name_str)
exit()

该程序的功能是实现简单的树莓派或者其他设备与服务器的通信,执行简单的插入、删除功能,其他的可以自行添加。测试的时候有几点需要注意:
①请确保你的服务器的公网地址等信息正确无误。
②请确保你的数据库已经创建了该表并且表里的元素一一对应,而且需要开启运行修改的权限。
③请确保你的服务器的端口正常,如果不能正常连接,检查一下你的服务器 的防火墙是否阻挡了你的设备访问,可以关闭或者设置运行通过。

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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存