python编程实例之插入数据

发布时间:2020-03-28编辑:脚本学堂
本文分享一例python代码,使用MySQLdb模块将数据插入到数据库中,学习下MySQLdb模块的用法,感兴趣的朋友参考下。

本节内容:
python mysqldb/ target=_blank class=infotextkey>MySQLdb 插入数据

今天来学习python 编程实例中,插入数据到数据库中的方法,有兴趣的朋友不要错过。

有关MySQLdb模块连接mysql数据库的方法,可以参考我们曾介绍过的一篇文章:python使用MySQLdb连接MySQL数据库,有了以上内容的铺垫,就比较容易理解以下的代码。

例子:
 

复制代码 代码示例:

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

db= MySQLdb.connect(host="localhost", user="python-test", passwd="python",
db="python-test")
try:
    title = raw_input("Please enter a book title: ")
    if title == "" :
        exit
    author = raw_input("Please enter the author's name: ")
    pubdate = int( raw_input("Enter the publication year: ") )
except:
    print "Invalid value"
    exit

print "Title: [" + title + "]"
print "Author: ["+ author + "]"
print "Publication Date: " + str(pubdate)

cursor = db.cursor()

stmt = "INSERT INTO Books (BookName, BookAuthor, PublicationDate) VALUES ('"
stmt = stmt + title
stmt = stmt + "', '"
stmt = stmt + author
stmt = stmt + "', "
stmt = stmt + str(pubdate)
stmt = stmt + ")"
cursor.execute(stmt)
print "Record added!"

cursor.close ()
db.commit ()

就是这么简单,在python中使用MySQLdb模块连接数据库,并插入数据,希望对大家有帮助。