简答题 偏难
#4890

使用Python的sqlite3库完成以下操作: 1.创建一个名为cpu的数据库文件,并创建一张Rate的表(表有三个字段:ID、Rate、updatetime…

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

未登录也能判分,登录后才会记录
答案与解析
正确答案:<pre class="brush:python;toolbar:false">#参考程序: 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()</pre><p><br/></p>
解析

评分标准:

(1)cpu.db;(2分)

(2)cur = conn.cursor();(3分)

(3)execute;(2分) 

(4)cur.close()。(3分)