python MySQLdb 对mysql基本操作方法

时间:2020-12-09 08:37:59
 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import MySQLdb conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='',db='host')
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
reCout = cur.execute('select ip,name from host,user where user.name = "alex" and user.id=host.id')
nRet = cur.fetchall()
conn.commit()
cur.close()
conn.close()
print reCout
print nRet
for i in nRet:
print i['name'],i['ip'] """
#修改
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='123',db='host')
cur = conn.cursor()
reCout = cur.execute('update host set id=%s',(1,))
conn.commit()
cur.close()
conn.close()
print reCout
"""
"""
#删除
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='123',db='host')
cur = conn.cursor()
reCout = cur.execute('delete from host')
conn.commit()
cur.close()
conn.close()
print reCout
"""
"""
l = [
('192.168.1.107','2'),
('192.168.1.108','2'),
('192.168.1.109','2'),
('192.168.1.177','2'),
]
#插入多条数据
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='123',db='host')
cur = conn.cursor()
reCout = cur.executemany('insert into host(ip,id) values(%s,%s)',l) conn.commit()
cur.close()
conn.close()
print reCout
"""
"""
#插入单条数据
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='123',db='host')
cur = conn.cursor()
reCout = cur.execute('insert into host(ip,id) values(%s,%s)',('192.168.1.1','1')) conn.commit()
cur.close()
conn.close()
print reCout
"""