python编程实例之更新数据库

发布时间:2020-06-28编辑:脚本学堂
本文分享一例python代码,教大家使用MySQLdb模块实现mysql数据的更新操作,感兴趣的朋友可以参考下。

本节内容:
python mysqldb/ target=_blank class=infotextkey>MySQLdb模块更新数据。

本节我们学习python 编程实例中,使用MySQLdb模块更新数据库的方法。

有关 python MySQLdb操作mysql数据库的例子,大家可以先看看这篇文章,相信会有所帮助的。

来看今天的实例代码,如下:
 

复制代码 代码示例:

#!/usr/bin/python
#site: www.jb200.com
#
import MySQLdb
import MySQLdb.cursors

def get_column_name( data, prompt, names ) :
    value=-1
    while value == -1:
        idx = 1
        for col in data :
            print str(idx) + ": " + col
            names.append( col )
            idx = idx + 1
        value = int( raw_input(prompt) )
        if value < 1 or value >= idx :
            value = -1
    return value

conn = MySQLdb.Connect(
    host='localhost', user='python-test',
    passwd='python', db='python-test')
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

cursor.execute("SELECT * FROM books")
data = cursor.fetchone()

names = []
old_value = get_column_name( data, "Which column do you want to change records for? ", names )
names = []
new_value = get_column_name( data, "Which column do you want to change records to? ", names )

old_val = raw_input("What value do you want to change for " + names[old_value-1] + ": ")
new_val = raw_input("What value do you want to change to for " + names[new_value-1] + ": ")

stmt = "UPDATE books SET " + names[new_value-1] + " = '"+ new_val + "' WHERE " + names[old_value-1] + " = '" + old_val + "'"
print stmt
cursor.execute(stmt)
print "Rows affected: " + str(cursor.rowcount)

cursor.close()
conn.commit()
conn.close()

以上就是python MySQLdb模块更新数据库的例子,希望对大家了解与掌握MySQLdb模块的用法,提供一些帮助吧。