python MySQLdb
jopen
9年前
一、插入数据 import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('eddy','china')) conn.commit() cur.close() conn.close() print reCount 二、批量插入数据 import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() li =[ ('eddy','china'), ('eddy1','china'), ] reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li) conn.commit() cur.close() conn.close() print reCount 三、删除数据 import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() reCount = cur.execute('delete from UserInfo') conn.commit() cur.close() conn.close() print reCount 四、修改数据 import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() reCount = cur.execute('update UserInfo set Name = %s',('alin',)) conn.commit() cur.close() conn.close() print reCount 五、查数据 # ############################## fetchone/fetchmany(num) ############################## import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() reCount = cur.execute('select * from UserInfo') print cur.fetchone() print cur.fetchone() cur.scroll(-1,mode='relative') print cur.fetchone() print cur.fetchone() cur.scroll(0,mode='absolute') print cur.fetchone() print cur.fetchone() cur.close() conn.close() print reCount # ############################## fetchall ############################## import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb') cur = conn.cursor() reCount = cur.execute('select Name,Address from UserInfo') nRet = cur.fetchall() cur.close() conn.close() print reCount print nRet for i in nRet: print i[0],i[1]