python 操作 mysql
查询(两种方法):
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'") #返回受影响的行数,执行错误返回异常