欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Python 实现mysql数据库

程序员文章站 2024-01-08 19:09:16
...

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)

上一篇:

下一篇: