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‘") #返回受影响的行数,执行错误返回异常
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。