1

I tried to put data in to a table using variabels, as you can see down below in the code. When I'm running this piece of code I get the following error:

What I want the code to do is, get the data out of the parameters i'm giving in to the function insert_data. And then using the wildcard questionmark symbol. To get the option to use the variabels as data. Not quite sure if it's the most propper way of doing so. But it does work in other occations. I just don't get why it does not work in this piece of code.

Traceback (most recent call last):
  File "{path}", line 65, in <module>
    insert_data()
  File "{path}", line 56, in insert_data
    query ("INSERT INTO computers (name, os, mac_addr) VALUES "
  File "{path}", line 8, in query
    cursor.execute(query, args)
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

MY CODE

import cgi
import sqlite3
from os import path, environ

def query(query, *args):
    db = sqlite3.connect(database)
    cursor = db.cursor()
    cursor.execute(query, args)
    resultaat = cursor.fetchall()
    db.commit()
    db.close()
    return resultaat

def database_create():
    if path.isfile(database) != True:
        query("CREATE TABLE 'computers' ('name' TEXT, 'os' TEXT, 'mac_addr' TEXT,"
                         "'create_date' timestamp DEFAULT current_timestamp)")
        query("CREATE TABLE 'data' ('computer_id' integer, 'mem_usage' float,"
                         "'cpu_usage' float, 'total_size' float, 'used_size' float, 'free_size' float,"
                         "'create_date' timestamp DEFAULT current_timestamp)")
        query("CREATE TABLE 'grafieken' ('name' TEXT, 'legend' TEXT)")
        query("CREATE TABLE 'gebruikers'('u_name' TEXT, 'p_word' TEXT)")
        query("INSERT INTO 'gebruikers' (u_name, p_word) VALUES ('beheerder',"
              "'695badbd075fdacd8638a600712f9aec74dd85b6ae61f7ab7f0f45e438196bf0aac117102d328e3d4e92fd5fc78f593a50875f900a7fe59f5d463bbf35af245c3b605ec3b6f91cbec7452801ca5ca95ebf00b248e73d07b9934d25ab21b6943a83d1944450854ef05044be01ff0d3b72b158209a70a28c3e063ec6a7f806d610')")
        query("INSERT INTO grafieken VALUES ('Totale hardeschijf ruimte', 'Ruimte (GB), hoger is beter')")
        query("INSERT INTO grafieken VALUES ('Beschikbare hardeschijf ruimte', 'Ruimte (GB), hoger is beter')")
        query("INSERT INTO grafieken VALUES ('Gebruikte hardeschijf ruimte', 'Ruimte (GB), lager is beter')")
        query("INSERT INTO grafieken VALUES ('Geheugenverbruik', 'Geheugen (%), lager is beter')")
        query("INSERT INTO grafieken VALUES ('CPU-verbruik', 'Processor (%), lager is beter')")
        print ('done')
    elif path.isfile(database) == True:
        print ('DB already exists')
    else:
        print('failed')

def insert_data():
    try:
        import psutil
    except ImportError:
        print('no psutil installed')
        exit(1)
    import platform
    import uuid

    diskspace = psutil.disk_usage('/')
    spacetoGB = [diskspace[0] // (2 ** 30), diskspace[1] // (2 ** 30), diskspace[2] // (2 ** 30)]  # Total, used, free
    name = platform.uname()[1],
    mac_addr = '%012x' % uuid.getnode(),  # https://stackoverflow.com/questions/13864608/get-mac-address-in-python-and-append-to-string
    #totalsize = spacetoGB[0],
    #usedsize = spacetoGB[1],
    #freesize = spacetoGB[2],
    os = platform.system() + " " + platform.release(),
    # memusage = psutil.virtual_memory().percent,
    # cpu_usage = psutil.cpu_percent(interval=1)

    query ("INSERT INTO computers (name, os, mac_addr) VALUES "
           "(?,?,?)", *(name, os, mac_addr,))
    data = 'Record added'
    print (data)
    #return data


database = "tester.db"
database_create()
insert_data()
3
  • Unrelated but opening and closing a database for each query is an anti-pattern... Commented Jan 4, 2022 at 17:58
  • What do you mean with anti-pattern... Kinda interested in why you say that ;o Commented Jan 5, 2022 at 13:22
  • Opening and closing a database is generally a rather expensive operation. It should be done only once in a program, or for transactional application at most once per transaction - and even for real world transactional applications the database connections are pooled to be re-used over a number of transactions. Doing that for each access could be done (and if often done by beginners) but does not meet recommended practices. That is why it is called an anti-pattern... Commented Jan 5, 2022 at 13:29

1 Answer 1

4

The commas (,) terminating the set statments (eg name = platform.uname()[1],) cast the variables as tuples.

Sign up to request clarification or add additional context in comments.

2 Comments

You are such a hero! Thank you very much! It's a dumb mistake, but a mistake anyhow! Thanks a lot!
You're welcome. Not so much a mistake, rather "school" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.