2012-04-24 54 views
0

有我书面方式在Python一个简单的应用程序,将监视我的CPU的使用率和内存,把它变成一个MySQL数据库在这里将来的处理是我的代码:Python的MySQLdb的插入问题

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

这里

-- 
-- 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 ; 

但是我做一个INSE时,一时无法修复此错误:我使用为monitoring

下面是MySQL数据库的转储的libary RT:

_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") 

任何提示解决此问题? 对不起,但我是新来的蟒蛇:)

在此先感谢。

回答

1

这不是Python问题。问题是usage是MySQL中的保留字。你应该改变你的专栏的名称,或使用反引号在你的代码中引用它:

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

蟒蛇的神圣母亲,我不知道这一点。固定之后,它像魅力一样运作。非常感谢你。 – 2012-04-24 23:04:52