怎样使用MySQL和Python实现一个简单的博客系统
要使用MySQL和Python实现一个简单的博客系统,可以依照以下步骤进行:
pip install mysql-connector-python
命令进行安装。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 %}
{{ POST@[1] }}
{{ POST@[2] }}
{% endfor %}
这只是一个简单的示例,你可以根据需求进行扩大和修改。
TOP