时间:2021-07-01 10:21:17 帮助过:1人阅读
上面使用cur.execute()方法插入一条记录,那么怎样批量插入数据记录呢.可以使用cur.executemany()
1 import MySQLdb 2 3 conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) 4 5 cur = conn.cursor() 6 7 li =[ 8 (‘alex‘,‘usa‘), 9 (‘sb‘,‘usa‘), 10 ] 11 reCount = cur.executemany(‘insert into UserInfo(Name,Address) values(%s,%s)‘,li) 12 13 conn.commit() 14 cur.close() 15 conn.close() 16 17 print reCount
二、删除数据
1 import MySQLdb 2 3 conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) 4 5 cur = conn.cursor() 6 7 reCount = cur.execute(‘delete from UserInfo‘) 8 9 conn.commit() 10 11 cur.close() 12 conn.close() 13 14 print reCount
三、修改数据
1 import MySQLdb 2 3 conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) 4 5 cur = conn.cursor() 6 7 reCount = cur.execute(‘update UserInfo set Name = %s‘,(‘alin‘,)) 8 9 conn.commit() 10 cur.close() 11 conn.close() 12 13 print reCount
四、查数据
1 # ############################## fetchone/fetchmany(num) ############################## 2 3 import MySQLdb 4 5 conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) 6 cur = conn.cursor() 7 8 reCount = cur.execute(‘select * from UserInfo‘) 9 10 print cur.fetchone() 11 print cur.fetchone() 12 cur.scroll(-1,mode=‘relative‘) 13 print cur.fetchone() 14 print cur.fetchone() 15 cur.scroll(0,mode=‘absolute‘) 16 print cur.fetchone() 17 print cur.fetchone() 18 19 cur.close() 20 conn.close() 21 22 print reCount
1 # ############################## fetchall ############################## 2 3 import MySQLdb 4 5 conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) 6 #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 7 cur = conn.cursor() 8 9 reCount = cur.execute(‘select Name,Address from UserInfo‘) 10 11 nRet = cur.fetchall() 12 13 cur.close() 14 conn.close() 15 16 print reCount 17 print nRet 18 for i in nRet: 19 print i[0],i[1]
python2.0_s12_day9_mysql操作
标签: