luoyonghao 发表于 2015-03-10 09:10

python操作mysql的问题,求前辈指导一下

本帖最后由 luoyonghao 于 2015-03-10 09:12 编辑

需求是这样的
我有一个日志文件 里面的内容大概为
sta-000.bat dongfang 192.168.1.1
sta-000.bat cctv8 192.168.1.3
sta-000.bat cctv8 192.168.1.3
sta-000.bat cctv8 192.168.1.3
sta-000.bat dongfang 192.168.1.1

我想把这里面的内容逐行插入到mysql数据库里,数据库表里有4个字段 分别为city channel time ip
我自己写了个代码import MySQLdb

db = MySQLdb.connect("localhost","root","admin","test1" )
cursor = db.cursor()

f = open('d:\\run.log')
for s in f.readlines():
        time = s
        channel = s
        city = 'shenyang'
        ip = s[-12:]
      cursor.execute('insert into run_log values("%s","%s","%s","%s")' % (city,channel,time,ip))
        db.commit()
        db.close()结果执行的时候程序报错
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/log.py", line 12, in <module>
    cursor.execute('insert into run_log values ("shenyang","dongfang","2015-03-07 19:20:20","192.168.1.1")')
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 180, in execute
    charset = db.character_set_name()
InterfaceError: (0, '')

现在我不知道问题出在哪里,或者哥哥们有什么更好的办法能实现这个功能,不胜感激!

huangxiaohen 发表于 2015-03-10 10:07

第一,db关闭你应该放到for外边。
然后,你这按字符个数取不科学啊,最简单的,一行字符串都按空格分割不就好了么.当然用正则也可以。

luoyonghao 发表于 2015-03-10 10:15

huangxiaohen 发表于 2015-03-10 10:07 static/image/common/back.gif
第一,db关闭你应该放到for外边。
然后,你这按字符个数取不科学啊,最简单的,一行字符串都按空格分割不就 ...
恩 我已经搞定了多谢!

页: [1]
查看完整版本: python操作mysql的问题,求前辈指导一下