使用MySQLdb操作MySQL資料庫
阿新 • • 發佈:2018-11-03
#coding:utf-8
import MySQLdb
# 1.連線資料庫
db = MySQLdb.connect('localhost','root','','students',charset='utf8')
cur = db.cursor()
# 2.插入資料
sql = "INSERT INTO USER (NAME, qq) VALUES ('左湃', '888');"
cur.execute(sql)
db.commit()
# 3.獲取查詢結果
cur.execute("select * from user")
result = cur.fetchall()
# 4. 刪除(delete)
try:
cur.execute("DELETE FROM `user` WHERE qq = '888'")
print "hello"
db.commit()#提交更改
except:
db.rollback() #撤銷更改
# 5. 更新(update)
try:
cur.execute("update user set qq = '2856' where qq = '9999'")
db.commit()
except:
db.rollback()
# 6:輸出查詢結果
for r in result:
print "%s %s %s" %r
cur.close()
db.close()