要使用MysqL和Python实现一个简单的博客系统,可以按照以下步骤进行:
-
安装MysqL数据库和Python的MysqL库:首先在你的机器上安装MysqL数据库,并且安装Python的MysqL库,可以使用
pip install mysql-connector-python
命令进行安装。 -
创建数据库和表:使用MysqL的命令行工具或者可视化工具(如PHPMyAdmin)创建一个名为"blog"的数据库,并在该数据库中创建一个名为"posts"的表,用于存储博客文章的信息。可以使用以下sql语句创建表:
CREATE TABLE posts (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
content TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
import MysqL.connector
# 连接到MysqL数据库
cnx = MysqL.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="blog"
)
请将"your_user"和"your_password"替换为你的MysqL用户名和密码。
def create_post(title, content):
# 创建一个游标对象
cursor = cnx.cursor()
# 执行插入语句
sql = "INSERT INTO posts (title, content) VALUES (%s, %s)"
val = (title, content)
cursor.execute(sql, val)
# 提交事务
cnx.commit()
# 关闭游标
cursor.close()
def get_posts():
# 创建一个游标对象
cursor = cnx.cursor()
# 执行查询语句
sql = "SELECT * FROM posts"
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
# 关闭游标
cursor.close()
# 返回查询结果
return result
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
# 查询博客文章
posts = get_posts()
# 渲染模板并返回结果
return render_template("index.html", posts=posts)
在模板文件(index.html)中,可以使用类似以下代码展示博客文章:
{% for post in posts %}
<h2>{{ post[1] }}</h2>
<p>{{ post[2] }}</p>
{% endfor %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。