Michał Lach
Michał Lach

Reputation: 1278

Python MySQLdb insert issue

there I am writting a simple app in Python that will monitor the usage of my cpu and ram and put it into a MySQL database for future processing here is my code :

import MySQLdb
import psutil


connection = MySQLdb.connect(host="localhost", port=8888, user="root", passwd="root", db="monitoring", unix_socket="/Applications/MAMP/tmp/mysql/mysql.sock")
c = connection.cursor()

while True:

    usage = psutil.cpu_percent(interval=1)

    c.execute("INSERT INTO cpu (usage) VALUES (%s)", (usage))

    c.execute("SELECT * FROM cpu")
    print c.fetchall()

Here is the libary that I am using for for monitoring

Here is a dump for MySQL database :

    --
-- Table structure for table `cpu`
--

    CREATE TABLE `cpu` (
      `id` int(12) NOT NULL AUTO_INCREMENT,
      `usage` float NOT NULL,
      `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2 ;

However I am unable to fix this error when making an INSERT :

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) VALUES (12.9)' at line 1")

Any tips to fix this ? I am sorry, but I am new to Python :)

Thanks in advance.

Upvotes: 0

Views: 757

Answers (1)

Ike Walker
Ike Walker

Reputation: 65527

This is not a Python issue. The problem is that usage is a reserved word in MySQL. You should either change the name of your column to something else, or use backticks to quote it in your code:

c.execute("INSERT INTO cpu (`usage`) VALUES (%s)", (usage))

Upvotes: 1

Related Questions