简体   繁体   中英

sqlite3.OperationalError: no such column: sudo

I'm exploring sqlite3 in python by adding values of ps -a in DB. However, Im getting the no such column: sudo error from my insert_sensor_reading() funtion.

I've tagged the entire code just in case if anyone wants to cross verify

#!/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()

EDIT: Below is the output of ps -a Im storing all the PID values in pidstr and all commands in cmdstr. the error is probably because of some error while storing sudo in cmdstr but Im not sure why is it happening.

  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

Your table row CMD is defined as datatype TEXT. However, in your insert statement you actually pass sth like:

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

while it needs to be

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] +"');"

IMPORTANT : interpolating the query strings yourself is NOT recommended for security reasons. Rather use the execute method accordingly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM