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 文件读写操作实例详解

一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法。1.得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()2.返回指定目录下...

Python pandas常用函数详解

本文研究的主要是pandas常用函数,具体介绍如下。 1 import语句 import pandas as pd import numpy as np import matplot...

Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。 关于时间戳的几个概念 时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移...

python2.7读取文件夹下所有文件名称及内容的方法

最近稍稍有点空闲时间,于是重新温习了一下之前学习过的python基础。废话不多说,记录一下自己的所得。 首先,安装什么的不在本人的温习范围,另,本人使用的是windows下的python...

Python绘制股票移动均线的实例

Python绘制股票移动均线的实例

1. 前沿 移动均线是股票最进本的指标,本文采用numpy.convolve计算股票的移动均线 2. numpy.convolve numpy.convolve(a, v, mode='...