Python自动化(七)使用MySQLdb操作MySQL数据库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gavinsun/article/details/78055180
#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()

# 5.输出查询结果
for r in result:
    print "%s    %s    %s" %r

cur.close()
db.close()


猜你喜欢

转载自blog.csdn.net/gavinsun/article/details/78055180