当前位置:编程学习 > 网站相关 >>

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.zzzyk.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()  
 
 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,