刷题刷出新高度,偷偷领先!偷偷领先!偷偷领先! 关注我们,悄悄成为最优秀的自己!

简答题

使用Python的sqlite3库完成以下操作:

1.创建一个名为cpu的数据库文件,并创建一张Rate的表(表有三个字段:ID、Rate、updatetime)

2.记录下十秒钟cpu相关数据,并删除第id为1的数据。

import sqlite3

import datetime
import psutil #获取cpu当前占比
conn = sqlite3.connect("++++++++ ")
creatsql = “create table Rate(ID integer primary key, Rate float,updatetime time)”
++++++++
cur.execute(creatsql)
conn.commit()
insertsql = “insert into Rate(ID,Rate,updatetime) values(%d,%f,‘%s’)”
checksql = “select * from Rate”
for x in range(0,10):
nowtime = datetime.datetime.now()
nowtime = nowtime.strftime(‘%Y-%m-%d %H:%M:%S’)
cpu_per = float(psutil.cpu_percent(1))
cur.++++++++ (insertsql % (x,cpu_per,nowtime))
conn.commit()
cur.execute(checksql)
data = cur.fetchall()
delsql=“delete from Rate where ID=%d”
cur.execute(delsql %1)
conn.commit()
++++++++
conn.close()

使用微信搜索喵呜刷题,轻松应对考试!

答案:

参考程序:

import sqlite3 import datetime import psutil conn = sqlite3.connect(“cpu.db”) creatsql = “create table Rate(ID integer primary key, Rate float,updatetime time)” cur = conn.cursor() cur.execute(creatsql) conn.commit() insertsql = “insert into Rate(ID,Rate,updatetime) values(%d,%f,‘%s’)” checksql = “select * from Rate” for x in range(0,10): nowtime = datetime.datetime.now() nowtime = nowtime.strftime(‘%Y-%m-%d %H:%M:%S’) cpu_per = float(psutil.cpu_percent(1)) cur.execute(insertsql % (x,cpu_per,nowtime)) conn.commit() cur.execute(checksql) data = cur.fetchall() delsql=“delete from Rate where ID=%d” cur.execute(delsql %1) conn.commit() cur.close() conn.close()

解析:

【喵呜刷题小喵解析】:1. 首先,我们导入了sqlite3、datetime和psutil这三个库。2. 然后,我们创建了一个名为"cpu.db"的数据库连接。3. 接着,我们定义了一个创建表的SQL语句,并创建了一个游标对象cur。4. 使用cur.execute()执行创建表的SQL语句,并使用conn.commit()提交事务。5. 定义了一个插入数据的SQL语句和一个查询数据的SQL语句。6. 在for循环中,我们获取当前时间,获取CPU使用率,并使用cur.execute()执行插入数据的SQL语句,每次插入后都使用conn.commit()提交事务。7. 在循环结束后,我们使用cur.execute()执行查询数据的SQL语句,并使用cur.fetchall()获取所有数据。8. 定义了一个删除数据的SQL语句,并使用cur.execute()执行删除数据的SQL语句,删除id为1的数据,并使用conn.commit()提交事务。9. 最后,我们关闭了游标和数据库连接。注意:在Python中,字符串内的单引号需要使用转义字符'\'来表示,否则会导致语法错误。因此,在插入数据的SQL语句中,我们将时间格式字符串中的单引号用'\lsquo;''和'\rsquo;'表示。另外,为了保证代码的正确性和安全性,我们应该在每次执行完SQL语句后都及时关闭游标,因此,在代码的最后添加了cur.close()语句来关闭游标。
创作类型:
原创

本文链接:使用Python的sqlite3库完成以下操作: 1.创建一个名为cpu的数据库文件,并创建一张Ra

版权声明:本站点所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明文章出处。

让学习像火箭一样快速,微信扫码,获取考试解析、体验刷题服务,开启你的学习加速器!

分享考题
share