python简单实现操作Mysql数据库

yipeiwu_com6年前Python基础

用python编写数据库的代码很方便,但是如果不想自己写sql语句,其实还有更多的讨巧办法。使用webpy的db库就是不错的一个选择。当然为了使用webpy的db,之前你还需要安装MySQLdb,其他的就不需要做什么了。

1、安装MySQLdb库

sudo apt-get install python-MySQLdb

2、安装webpy

sudo apt-get install python-webpy

3、连接数据库

import web

db = web.database(dbn='mysql', db='blog', user='root', pw='123456')

4、增、删、改、查数据

def get_pages():
  return db.select('pages', order='id DESC')

def get_page_by_url(url):
  try:
    return db.select('pages', where='url=$url', vars=locals())[0]
  except IndexError:
    return None

def get_page_by_id(id):
  try:
    return db.select('pages', where='id=$id', vars=locals())[0]
  except IndexError:
    return None

def new_page(url, title, text):
  db.insert('pages', url=url, title=title, content=text)

def del_page(id):
  db.delete('pages', where="id=$id", vars=locals())

def update_page(id, url, title, text):
  db.update('pages', where="id=$id", vars=locals(),
    url=url, title=title, content=text)

其中db的table设计为,

CREATE TABLE pages (
  id INT AUTO_INCREMENT,
  url TEXT,
  title TEXT,
  content TEXT,
  primary key (id)
);

5、注意事项

在web.database创建的时候,其实此时没有连接,只是设置了dbn、db、user、password这些基本属性,只有select、insert、delete、update的时候才会进行连接。

6、其他资源

建议大家直接到webpy 官网 看示例代码,这样学的更快一些。关于MySQLdb的操作,大家可以看这一篇 链接

相关文章

python利用wx实现界面按钮和按钮监听和字体改变的方法

python利用wx实现界面按钮和按钮监听和字体改变的方法

wxPython是Python语言的一套优秀的GUI图形库。允许Python程序员很方便的创建完整的、功能键全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wxWidge...

Python验证码识别的方法

本文实例讲述了Python验证码识别的方法。分享给大家供大家参考。具体实现方法如下: #encoding=utf-8 import Image,ImageEnhance,ImageF...

Python3 实现串口两进程同时读写

通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出 import threading,time import serial import str...

python中模块的__all__属性详解

python模块中的__all__属性,可用于模块导入时限制,如: from module import * 此时被导入模块若定义了__all__属性,则只有__all__内指定的属...

python实现在遍历列表时,直接对dict元素增加字段的方法

example: for item in warehouse_list: warehouse_id = item['warehouse_id'] warehous...