Webpy_web.database Module
There are two ways to use the MySQL management database in the WEBPY framework, one is to use the MySQLdb module in Python:
Import MySQLdb
There is also a web.database module with Webpy, the function is basically the same as the MySQLdb module:
Import webdb = Web.database ( dbn = ' mysql ', user = ' root ', pw = ' password ', db = ' db_name ', )
Above is the creation of a database object db, the parameter user is the username, PW is the password, DB is the database name
The DB object supports the following operations:
- Insert
- Select
- Update
- Delete
- Multiple inserts
- Advanced querying
- Joining tables
Inserting
Build a table first Todos
CREATE TABLE users ( ID int primary key auto_increment, name nchar, password nchar), address NCHAR (20))
Insert an item of data:
Db.insert (' users ', name = ' Bob ', password = ' 123 ', address = ' Zhuhai ')
selecting
Select returns an object of type ' Web.iterbetter ', which can be converted to list () for processing, the element of each list is the storage type, similar to the Python dictionary, can be directly through the keyword to get the desired value
Users = List (Db.select (' Users ', where= "id>10")) print users[0][' name '] ' Bob '
Updating
num_updated = Db.update (' users ', where= "id = ten", address = ' Guangzhou ')
The return value is the modified number of rows
deleting
Db.delete (), as with update () usage
Advanced querying
If you are familiar with MySQL statements, you can directly execute the MySQL statement directly:
Results = List (Db.query ("SELECT * from users where name = '%s '"% ' Bob ')) print results[0][' name '], results[0][' address '] ' B OB ', ' Zhuhai '
Webpy using MySQL database operations (web.database)