码迷,mamicode.com
首页 > 数据库 > 详细

python 操作 mysql

时间:2015-05-08 16:41:46      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

查询(两种方法):

import MySQLdb  
  
conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "root", db = "fish")  
cursor = conn.cursor ()  



cursor.execute ("SELECT * FROM polls_poll")
rows = cursor.fetchall()    #获取所有结果集
for row in rows:            #从结果集中一条一条读出来
    print "%d, %s, %s" % (row[0], row[1], row[2])
  
print "Number of rows returned: %d" % cursor.rowcount  



cursor.execute ("SELECT * FROM polls_poll")  
while (True):  
    row = cursor.fetchone()    #从结果集的开始,获取一条记录, 移动一下游标,直到结束返回None
    if row == None:  
        break  
    print "%d, %s, %s" % (row[0], row[1], row[2])
      
print "Number of rows returned: %d" % cursor.rowcount  



cursor.close ()  
conn.close ()

插入:

cursor.execute ("INSERT INTO two(name, age) VALUES (‘bill‘, 18)")  #返回受影响的行数,执行错误返回异常

更新:

cursor.execute ("UPDATE two SET name = ‘jack‘, age = ‘22‘ WHERE name = ‘bill‘")  #返回受影响的行数,执行错误返回异常





python 操作 mysql

标签:

原文地址:http://my.oschina.net/u/861926/blog/412322

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!