Python轻量级WEB框架web.py之操作数据库

以MYSQL做示例:

pip install pymysql
如果安装超时或其他原因不成功,选择下面的站点来安装
pip install -i https://pypi.douban.com/simple pymysql

5.7版本的mysql,安装之后有问题,没有服务,也没有data和my.ini
my.ini
[client]
port = 3306
[mysql]
default-character-set=utf8
[mysqld]
port=3306
basedir="C:/Program Files (x86)/MySQL/MySQL Server 5.7"
datadir="C:/Program Files (x86)/MySQL/MySQL Server 5.7/data"
character_set_server=utf8
default-storage-engine=INNODB

管理员命令行来到C:\Program Files (x86)\MySQL\MySQL Server 5.7\bin之后

mysqld.exe install     安装服务 
mysqld -initialize    新建data以及安装数据库

第一次生成的随机密码在XXB-TONY.err文件最后
2019-11-29T13:24:23.648405Z 1 [Note] A temporary password is generated for root@localhost: 8Zue9Oa2to!e
mysql -u root -p
8Zue9Oa2to!e
进入之后修改密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';


创建数据库,表和一些测试数据
CREATE DATABASE tonytest;
USE tonytest;
CREATE TABLE articles(id int,title varchar(20));
INSERT INTO articles VALUES(1,'大日经疏');
INSERT INTO articles VALUES(3,'六祖法宝坛经');
INSERT INTO articles VALUES(4,'佛陀传');

dbtest.py 

# -*- coding: utf-8 -*-  
import web
# import MySQLdb #python2
# import MySQLdb.cursors
import pymysql #python3
#pymysql.install_as_MySQLdb()

render = web.template.render('templates/')
#模糊匹配范围小的在前面
urls = (
    '/article','article',
    '/index', 'index',
    '/blog/\d+','blog',
    '/(.*)','view'
)
app = web.application(urls, globals())
class index:
    def GET(self):
        return web.seeother('/article') 
        #return web.seeother('https://www.baidu.com')
class blog:
    def GET(self):
        return web.ctx.env
    def POST(self):
        data = web.input()
        return data
class view:
    def GET(self, name):
         return open(r'templates/article.html').read()
class article:
    def GET(self):
        conn=pymysql.connect(host='localhost',user='root',passwd='root',db='tonytest',cursorclass=pymysql.cursors.DictCursor)
        cur=conn.cursor()
        cur.execute('SELECT * FROM articles')
        res=cur.fetchall()
        cur.close()
        conn.close()
        print(res)#[{'id': 1, 'title': '大日经疏'}, {'id': 3, 'title': '六祖法宝坛经'}, {'id': 4, 'title': '佛陀传'}]
        return  render.article(res)
if __name__ == "__main__":
    app.run()

 article.html

$def with(res)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />  
<title>article</title>
</head>
<body>
<ul>
$for r in res:
    <li>$r.get('id') ---- $r.get('title')</li>
</ul>
</body>
</html>

python dbtest.py 9998
http://localhost:9998/article

上面是读取数据,下面做个插入数据的示例:

 insert.html,插入数据的输入页面

<html>
<head>
<title>INSERTTEST</title>
</head>
<body>
    <form action="/adddel" method="POST">
       ID:<input type="text" name="bookid" value="">
       TITLE:<input type="text" name="booktitle" value="">
        <input type="submit" value="submit">
    </form>
</body>
</html>

dbtest.py

import web
import pymysql #python3

render = web.template.render('templates/')
urls = (
    '/add','add',
    '/adddel','adddel', 
    '/article','article'
)
app = web.application(urls, globals())

class add:
    def GET(self):
        return open(r'templates/insert.html').read()
class adddel:
    def POST(self):
        data = web.input()
        #return data
        bid=data.bookid
        btitle=data.booktitle
        conn=pymysql.connect(host='localhost',user='root',passwd='root',db='tonytest',cursorclass=pymysql.cursors.DictCursor)
        cur=conn.cursor()
        cur.execute("INSERT INTO articles(id,title) VALUES("+bid+",'"+btitle+"')")
        conn.commit()
        cur.close()
        conn.close()
        return web.seeother('/article') 
        #return "INSERT INTO articles(id,title) VALUES("+bid+",'"+btitle+"')"
class article:
    def GET(self):
        conn=pymysql.connect(host='localhost',user='root',passwd='root',db='tonytest',cursorclass=pymysql.cursors.DictCursor)
        cur=conn.cursor()
        cur.execute('SELECT * FROM articles')
        res=cur.fetchall()
        cur.close()
        conn.close()
        return  render.article(res)
if __name__ == "__main__":
    app.run()

其中插入数据需要注意conn.commit()提交,不然插入不了不会生效

python dbtest.py 9922
http://127.0.0.1:9922/add

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅恪光潜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值