时间:2021-07-01 10:21:17 帮助过:21人阅读
Python实现的mysql数据库操作,对数据库指定表进行查询,删除,插入,更新等等。并且牢记db = web.database(dbn='mysql',db='py',user='root',pw='123456')。 1.简单 #-*- coding:utf-8 -*- ''' @author:cuiruiqiang @date:2014-12-05 @filename:testDatabas
Python实现的mysql数据库操作,对数据库指定表进行查询,删除,插入,更新等等。并且牢记db = web.database(dbn='mysql',db='py',user='root',pw='123456')。
1.简单
#-*- coding:utf-8 -*-
'''
@author:cuiruiqiang
@date:2014-12-05
@filename:testDatabase.py
'''
import web
import sys
#define a database object 定义一个数据库对象
db = web.database(dbn='mysql',db='py',user='root',pw='123456')
#define a table 定义一个表
tb = 'student'
def get_by_id(id):
s = db.select(tb,where='id=$id',vars=locals())
if not s:
return False
return s[0]
if __name__ == '__main__':
resultValue=get_by_id(3)
print resultValue
print db
2.比较复杂,引入mysql操作语言select ,update,insert, delete
#-*- coding:utf-8 -*-
'''
@author:cuiruiqiang
@date:2014-12-07
@filename:testDatabase2.py
'''
import web
import sys
#define a database object
db = web.database(dbn='mysql',db='py',user='root',pw='123456')
#define a table
tb = 'student'
def getTableInfo(id):
result = db.query('select * from student where id>=$id',vars=locals())
for s in result:
print s.id,s.name,s.age,s.address
if __name__ == '__main__':
#simple select
result = db.query('select * from student where id>$id',vars={'id':1})
for s in result:
print s.id,s.name,s.age,s.address
#insert
db.insert('student',id=4,name='lijliang',age=32,address='Hebei baoj')
getTableInfo(2)
#update
db.update('student',where='id=$id',vars={'id':2},name='xiaom')
getTableInfo(2)
#delete
db.delete('student',where='id=$id',vars={'id':1})
getTableInfo(2)