python操作mysql
python通过MySQLdb模块编辑mysql数据库,python3使用pymysql模块
添加数据
1 import pymysql 2 3 conn = pymysql.connect(host='127.0.0.1',user='root',passwd='xilehang99',db='liyaoguo') 4 5 cur = conn.cursor() 6 7 reCount = cur.execute('insert into students(name,sex,age,tel,nal) values(%s,%s,%s,%s,%s)',('jack','F',23,123456,'chain')) 8 9 conn.commit() 10 11 cur.close() 12 conn.close() 13 14 print (reCount)
查看数据
1 import pymysql 2 3 conn = pymysql.connect(host='127.0.0.1',user='root',passwd='xilehang99',db='liyaoguo') 4 5 cur = conn.cursor() 6 7 reCount = cur.execute('select * from students') #查询表内容 8 9 conn.commit() 10 11 cur.close() 12 conn.close() 13 14 print (reCount) 15 print(cur.fetchone()) #获取一条结果 16 print(cur.fetchmany(2)) #获取前两条结果 17 print(cur.fetchall()) #获取所有结果
修改数据
1 import pymysql 2 3 conn = pymysql.connect(host='127.0.0.1',user='root',passwd='xilehang99',db='liyaoguo') 4 5 cur = conn.cursor() 6 7 reCount = cur.execute('update students set Name = %s',('alin',)) #修改数据 8 reCount = cur.execute('delete from students') #删除数据 9 10 conn.commit() 11 12 cur.close() 13 conn.close() 14 15 print (reCount)