标签:集中 name 序列 关闭 exce 约束 eve sele 而不是
import MySQLdb conn = MySQLdb.connect(host=‘localhost‘,user=‘weiyz‘,passwd=‘123456‘,db=‘test_DB‘,charset=‘utf-8‘) #创建一个游标对象 cur = conn.cursor() #执行SQL语句,注意这里不返回结果,只是执行而已 cur.excute("use test_table;show tables;") #方法一:fetchall方法返回所有匹配的元组,给出一个大元组(每个元素还是一个元组) ress = cursor.fetchall() #方法二:fetchone方法返回一条数据,并且使游标右移,若没有返回None res = cursor.fetchone() while res: print res res = cursor.fetchone() db.close()
SQL = """ select * from Client where level > %d and gid = %s """ cur.execute(SQL,(2,‘10001‘)) #如果只有一个变量,args不要写类似 (‘10001‘)这样,因为这判是<type ‘str‘>而不是tuple,应该写(‘10001‘,) print cur.fetchone() ##如果同样的SQL,用executemany来查询多个结果集的话 cur.executemany(SQL,((2,‘10001‘),(2,‘10002‘),(1,‘10003‘),)) #如此就相当于依次把2,10001;2,10002和1,10003约束给SQL在执行,但是从查询数据的角度来看,只能得到10003的数据, #因为executemany是一口气执行完的,fetch只能fetch到最后一个数字。
扩展:
SQL = "DELETE FROM Client WHERE level < %d" con = MySQLdb.connect(xxxxx) cur = con.cursor() try: cur.execute(SQL,(2,)) con.commit() except Exception,e: con.rollback() finally: cur.close() con.close()
标签:集中 name 序列 关闭 exce 约束 eve sele 而不是
原文地址:https://www.cnblogs.com/ShadowCharle/p/10695297.html