python数据库操作


1.简单例子
[python]  
#-*-coding:UTF-8-*-  
import MySQLdb  
db=MySQLdb.connect(host='localhost',user='root',passwd='root')  #成功则返回一个连接对象  
cur=db.cursor()     #创建一个光标来执行sql语句  
cur.execute('select version()') #执行SQL语句  
row=cur.fetchone()  #得到一个结果元组  
print 'server version:' ,row[0]  
cur.close()  
db.close()  
 
2.例子二
[python]  
#-*-coding:UTF-8-*-  
import MySQLdb  
import sys  
db=MySQLdb.connect(host='localhost',user='root',passwd='root',db='chen')  #成功则返回一个连接对象  
cursor=db.cursor()  
cursor.execute('drop table if exists animal')  
cursor.execute('create table animal(name   char(40),category char(40))')  
cursor.execute("insert into animal(name,category) values ('snake','reptile'),('frog','amphibian')")  
cursor.execute ("SELECT name, category FROM animal")  
while (1):  www.2cto.com
    row = cursor.fetchone()  
    if row == None:  
         break  
    print "%s, %s" % (row[0], row[1])  
print "Number of rows returned: %d" % cursor.rowcount  
db.commit()  
db.close()  
 
 

相关内容

    暂无相关文章

评论关闭