webpy使用mysql資料庫操作(web.database)

來源:互聯網
上載者:User

標籤:字典   mysql   一個資料庫   creat   rem   body   user   address   har   

webpy_web.database模組

webpy架構中使用mysql管理資料庫有兩種方法,一種是使用python裡面的MySQLdb模組:

import MySQLdb

 

還有一種就是用webpy內建的web.database模組,實現的功能與MySQLdb模組基本一樣:

import web db = web.database(        dbn = ‘mysql‘,        user = ‘root‘,        pw = ‘password‘,        db = ‘db_name‘,        )
 

上面是建立一個資料庫物件db,參數user為使用者名稱,pw為密碼,db為資料庫名

 

db對象支援以下操作:

  • insert
  • select
  • update
  • delete
  • multiple inserts
  • advanced querying
  • joining tables
inserting

先建一個表todos

create table users(        id int primary key auto_increment,        name nchar(20),        password nchar(20),        address nchar(20))

  

插入一項資料:

db.insert(‘users‘, name = ‘Bob‘, password = ‘123‘, address = ‘Zhuhai‘)

  

selecting

select返回的是‘web.iterbetter‘類型的對象,可以轉化為list()來進行處理,每個list的元素是Storage類型,類似與python的字典,可以直接通過關鍵字來得到需要的值

users = list(db.select(‘users‘, where="id>10"))print users[0][‘name‘] ‘Bob‘
updating
num_updated = db.update(‘users‘, where="id = 10", address = ‘Guangzhou‘)

傳回值是修改的行數

deleting

db.delete(), 與update() 用法一樣

advanced querying

如果對mysql語句比較熟悉的可以直接直接執行mysql語句:

results = list(db.query("select * from users where name = ‘%s‘" % ‘Bob‘))print results[0][‘name‘], results[0][‘address‘] ‘Bob‘, ‘Zhuhai‘
 

webpy使用mysql資料庫操作(web.database)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.