sqlite3.OperationalError:没有这样的列:sudo

时间:2018-04-13 08:52:31

标签: python sqlite

我在python中通过在DB中添加ps -a的值来探索sqlite3。但是,我得到了没有这样的专栏:来自insert_sensor_reading()功能的sudo错误。

我已经标记了整个代码,以防万一有人想要交叉验证

#!/usr/bin/python

import sqlite3
import subprocess

dbConn = None

#create table Reading
def create_table_reading():
    dbConn.execute('''CREATE TABLE  IF NOT EXISTS MYTABLE
        (PID            INT            NOT NULL,
         CMD            TEXT           NOT NULL);''')
    print "Created";

#Insert sensor reading
def insert_sensor_reading():   
    for i in range(0,l):
        query =  "INSERT INTO MYTABLE (PID,CMD) \
                  VALUES (" + pidstr[i] +  ","+ cmdstr[i] +");"
        i = i + 1
        dbConn.execute(query)
        dbConn.commit()
        print "inserted";

#read from table
def select_sensor_reading():
    query = "SELECT * FROM MYTABLE;"
    cursor = dbConn.execute(query)
    for row in cursor:
        print "PID = ", row[0],"\n"
    print "read";

#read from shell
def read_from_shell():
    pid = subprocess.check_output("ps -a | awk '{print $1}'", shell =True)
    cmd = subprocess.check_output("ps -a | awk '{print $4}'", shell =True)

    pidstr = pid.splitlines( )
    cmdstr = cmd.splitlines()
    global pidstr,cmdstr,l
    pidstr = pidstr[1:]
    cmdstr = cmdstr[1:]
    l=len(pidstr)


#Main
if __name__ == '__main__':

    dbConn = sqlite3.connect('test.db')
    print "Opened database successfully";
    read_from_shell()
    create_table_reading()
    insert_sensor_reading()
    select_sensor_reading()

编辑: 下面是ps -a Im的输出,将所有PID值存储在pidstr中,所有命令都存储在cmdstr中。错误可能是因为在cmdstr中存储sudo时出现了一些错误,但我不确定为什么会这样。

  PID TTY          TIME CMD
13280 pts/18   00:00:00 sudo
13281 pts/18   00:00:00 su
13282 pts/18   00:00:00 bash
17482 pts/17   00:00:00 ssh
19635 pts/19   00:00:00 ssh
24531 pts/1    00:00:00 sudo
24538 pts/1    00:00:00 su
24539 pts/1    00:00:00 bash

1 个答案:

答案 0 :(得分:2)

您的表行CMD被定义为数据类型TEXT。但是,在你的insert语句中,你实际上传递的是:

INSERT INTO MYTABLE (PID,CMD) VALUES (5, sudo)

虽然它需要

INSERT INTO MYTABLE (PID,CMD) VALUES (5, 'sudo')

# DO NOT DO IT LIKE THIS, SEE BELOW
query =  "INSERT INTO MYTABLE (PID,CMD) \
              VALUES (" + pidstr[i] +  ",'"+ cmdstr[i] +"');"

重要:出于安全原因,自行插入查询字符串不推荐。而是相应地使用execute方法:

dbConn.execute("INSERT INTO MYTABLE (PID,CMD) VALUES (?, ?)", (pidstr[i], cmdstr[i]))