python简单实现操作Mysql数据库

yipeiwu_com5年前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程序中解析并修改XML内容的方法

需求 在实际应用中,需要对xml配置文件进行实时修改, 1.增加、删除 某些节点 2.增加,删除,修改某个节点下的某些属性 3.增加,删除,修改某些节点的文本 使用xml文档 &l...

python连接MySQL、MongoDB、Redis、memcache等数据库的方法

用Python写脚本也有一段时间了,经常操作数据库(MySQL),现在就整理下对各类数据库的操作,如后面有新的参数会补进来,慢慢完善。 一,python 操作 MySQL:详情见:【ap...

python中map、any、all函数用法分析

本文实例讲述了python中map、any、all函数用法。分享给大家供大家参考。具体分析如下: 最近想学python,就一直比较关注python,昨天在python吧看到有个帖子提问怎...

对python读写文件去重、RE、set的使用详解

如下所示: # -*- coding:utf-8 -*- from datetime import datetime import re def Main(): sou...

Python实现大数据收集至excel的思路详解

一、在工程目录中新建一个excel文件 二、使用python脚本程序将目标excel文件中的列头写入,本文省略该部分的code展示,可自行网上查询 三、以下code内容为:实现从接口获取...