免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2068 | 回复: 7
打印 上一主题 下一主题

新手学python,刚写了个小脚本,不知哪里出了问题,大侠帮忙看看。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-03-10 17:46 |只看该作者 |倒序浏览
我的目的是从客户端数据库中抓数然后写入本地库中,select mon_ip from ip_list会找出两个ip,从第一个ip的数据库中抓取的数据可以正常写入,第二却不行,不知为什么循环没执行下去,求大侠解答?



cursor = conn.cursor()
cursor.execute("select mon_ip from ip_list")

while True:
    row = cursor.fetchone()
    if row == None:
        break

    print row[0]
    cli_conn = MySQLdb.connect(host = row[0],user = cli_user,passwd = cli_passwd,db = cli_db)
    cli_cursor = cli_conn.cursor()
    cli_cursor.execute("select VARIABLE_VALUE from GLOBAL_STATUS where VARIABLE_NAME='questions'")
    cli_row = cli_cursor.fetchone()
    cli_cursor.close()
    cli_conn.close()
    cursor.execute("insert into stat_log (mon_ip,time,questions) values(%s,now(),%s)",(row[0],cli_row[0]))

论坛徽章:
0
2 [报告]
发表于 2010-03-10 18:48 |只看该作者
1、第二条数据显示了吗?
print row[0]第二次执行了吗?
2、把cursor.execute("insert into stat_log (mon_ip,time,questions) values(%s,now(),%s)",(row[0],cli_row[0]))
换成conn.execute("insert into stat_log (mon_ip,time,questions) values(%s,now(),%s)",(row[0],cli_row[0]))
3、或者
rows = cursor.fetchall()  
for row in rows:

论坛徽章:
0
3 [报告]
发表于 2010-03-10 19:01 |只看该作者
没报错么?conn 连接需不需要显式commit?

论坛徽章:
0
4 [报告]
发表于 2010-03-10 19:05 |只看该作者
我用pyodbc连oracle   更改数据后需要conn.commit()。

论坛徽章:
0
5 [报告]
发表于 2010-03-10 19:58 |只看该作者
回2楼:第二条print row[0]也没显示,但把后面的语句都去掉是可以显示的。

回3,4楼:没有报错,我用的mysql myisam引擎,通常是不用commit的。

论坛徽章:
0
6 [报告]
发表于 2010-03-10 20:05 |只看该作者
本帖最后由 luffy.deng 于 2010-03-10 20:13 编辑

cursor.execute("insert into stat_log (mon_ip,time,questions) values(%s,now(),%s)",(row[0],cli_row[0]))
循环第一次cursor变了,循环第二次row = cursor.fetchone()就为假了。要么用一个新游标来执行insert,要么改一下程序逻辑。

论坛徽章:
0
7 [报告]
发表于 2010-03-10 20:08 |只看该作者
本帖最后由 luffy.deng 于 2010-03-10 20:10 编辑

你的程序逻辑是错误的,循环最后你更改了cursor,开始处却cursor.fetchone().
第二次循环row == None不可能为真。
row=cursor.fetchall()
for r in row:
    相关处理

论坛徽章:
0
8 [报告]
发表于 2010-03-10 20:51 |只看该作者
回复 7# luffy.deng


    谢谢指点,好像有点明白了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP