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求两点之间的直线距离(2种实现方法)

方法一: #导入math包 import math #定义点的函数 class Point: def __init__(self,x=0,y=0): self.x=x...

python requests指定出口ip的例子

爬虫需要,一个机器多个口,一个口多个ip,为轮询这些ip demo #coding=utf-8 import requests,sys,socket from requests_to...

numpy linalg模块的具体使用方法

最近在看机器学习的 LogisticRegressor,BayesianLogisticRegressor算法,里面得到一阶导数矩阵g和二阶导数Hessian矩阵H的时候,用到...

在Python中如何传递任意数量的实参的示例代码

1 用法 在定义函数时,加上这样一个形参 "*形参名",就可以传递任意数量的实参啦: def make_tags(* tags): '''为书本打标签''' print('标...

Python类属性的延迟计算

所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算。 优点 构造一个延迟计算属性的主要目的是为了提...