当前位置: 移动技术网 > IT编程>脚本编程>Python > python简单实现操作Mysql数据库

python简单实现操作Mysql数据库

2018年02月09日  | 移动技术网IT编程  | 我要评论

温德桥,孔繁森的女儿,窝里人

用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的操作,大家可以看这一篇 。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网