原文:http://chenxiaoyu.org/blog/archives/226 官网地址:http://webpy.org/ web.py是一个小巧灵活的框架,最新稳定版是0.33。这里不介绍web开发部分,介绍下关于数据库的相关操作。 很多Pyer一开始都喜欢自己封装数据库操作类,本人亦如此。不过后来通过
原文:http://chenxiaoyu.org/blog/archives/226
官网地址:http://webpy.org/
web.py是一个小巧灵活的框架,最新稳定版是0.33。这里不介绍web开发部分,介绍下关于数据库的相关操作。
很多Pyer一开始都喜欢自己封装数据库操作类,本人亦如此。不过后来通过观摩web.py的源码,发现其数据库操作部分相当紧凑实用。推荐懒人可以尝试一下。
废话不多,先来安装,有两种方式:
1. easy_install方式,如果木有此工具,可以参考:http://chenxiaoyu.org/blog/archives/23
easy_install web.py
2. 下载源码编译。地址: http://webpy.org/static/web.py-0.33.tar.gz ,解压后执行:
python setup.py install
web.py安装算到此结束,如果想使用其中的db功能,还得借助与相应数据库操作模块,比如MySQLdb、psycopg2。如果需要尝试连接池(database pool)功能,还得装下DBUtils。这几个模块都可以通过easy_install来安装。
下面开始使用吧!
1. 导入模块,定义数据库连接db。
import web db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='')
2. select 查询
# 查询表 entries = db.select('mytable') # where 条件 myvar = dict(name="Bob") results = db.select('mytable', myvar, where="name = $name") results = db.select('mytable', where="id>100") # 查询具体列 results = db.select('mytable', what="id,name") # order by results = db.select('mytable', order="post_date DESC") # group results = db.select('mytable', group="color") # limit results = db.select('mytable', limit=10) # offset results = db.select('mytable', offset=10)
3. 更新
db.update('mytable', where="id = 10", value1 = "foo")
4. 删除
db.delete('mytable', where="id=10")
5. 复杂查询
# count results = db.query("SELECT COUNT(*) AS total_users FROM users") print results[0].total_users # join results = db.query("SELECT * FROM entries JOIN users WHERE entries.author_id = users.id") # 防止SQL注入可以这么干 results = db.query("SELECT * FROM users WHERE id=$id", vars={'id':10})
6 多数据库操作 (web.py大于0.3)
db1 = web.database(dbn='mysql', db='dbname1', user='foo') db2 = web.database(dbn='mysql', db='dbname2', user='foo') print db1.select('foo', where='id=1') print db2.select('bar', where='id=5')
7. 事务
t = db.transaction() try: db.insert('person', name='foo') db.insert('person', name='bar') except: t.rollback() raise else: t.commit() # Python 2.5+ 可以用with from __future__ import with_statement with db.transaction(): db.insert('person', name='foo') db.insert('person', name='bar')

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
