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'")  #返回受影响的行数,执行错误返回异常

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8397.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论