python--如何操作表

>>> import MySQLdb
>>> conn=MySQLdb.connect(user='admin',passwd='',host='192.168.31.212')
>>> cur=conn.cursor() #创建游标
>>> conn.select_db('zsw')
第一种方法插入数据>>> cur.execute("insert into person(number,name,birthday) value(1,'zhaosunwei','1984-11-28')")
1L
第二种方法插入数据(推荐)>>> sqli="insert into person(number,name,birthday) value(%s,%s,%s)"
>>> cur.execute(sqli,(3,'liujilei','1982.05.06'))
1L
插入多条数据>> sqli="insert into person(number,name,birthday) values(%s,%s,%s)"
>>> cur.executemany(sqli,[(4,'sunjingbo','1964.08.01'),(5,'cuizhongjun','1964,11,29')])
2L
删除数据>>> cur.execute('delete from person where number=4')
1L
更新数据>>> cur.execute("update person set name='sunbo' where number=3")
1L
选择数据>>> cur.execute("select * from person")
4L
一条一条的取数据>>> cur.fetchone()
(1L, 'zhaosunwei', datetime.date(1984, 11, 28))
>>> cur.fetchone()
(2L, 'cuixiuxiu', datetime.date(1987, 8, 13))
>>> cur.fetchone()
(3L, 'sunbo', datetime.date(1982, 5, 6))
>>> cur.fetchone()
(5L, 'cuizhongjun', datetime.date(1964, 11, 29))
>>> cur.fetchone()
游标移到最开始位置>>> cur.scroll(0,'absolute')
>>> cur.fetchone()
(1L, 'zhaosunwei', datetime.date(1984, 11, 28))
多条数据同时取>>> cur.fetchmany(cur.execute("select * from person"))
((1L, 'zhaosunwei', datetime.date(1984, 11, 28)), (2L, 'cuixiuxiu', datetime.date(1987, 8, 13)), (3L, 'sunbo', datetime.date(1982, 5, 6)), (5L, 'cuizhongjun', datetime.date(1964, 11, 29)))
游标关掉>>> cur.close()
链接关掉>>> conn.close()
原文地址:https://www.cnblogs.com/zhaosunwei/p/7230336.html