数据库和网页用Python交互
时间: 2024-03-28 09:12:03 浏览: 13
Python可以通过许多库与数据库进行交互,其中最常用的是`pymysql`和`sqlite3`库。这些库允许您使用Python操作和查询数据库。以下是一个使用`pymysql`库连接到MySQL数据库的示例:
```python
import pymysql
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='root',
password='password',
db='database_name')
# 创建游标对象
cursor = connection.cursor()
# 执行查询
cursor.execute("SELECT * FROM table_name")
# 获取结果
results = cursor.fetchall()
# 输出结果
for result in results:
print(result)
# 关闭连接
connection.close()
```
对于与网页的交互,Python同样也有很多库可以使用,比如`Flask`和`Django`。这些库允许您创建Web应用程序,并在其中包含数据库查询和操作。以下是一个使用`Flask`库创建一个简单Web应用程序的示例:
```python
from flask import Flask, render_template
import pymysql
app = Flask(__name__)
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='root',
password='password',
db='database_name')
# 创建路由
@app.route('/')
def index():
# 创建游标对象
cursor = connection.cursor()
# 执行查询
cursor.execute("SELECT * FROM table_name")
# 获取结果
results = cursor.fetchall()
# 关闭游标
cursor.close()
# 渲染模板并返回结果
return render_template('index.html', results=results)
# 关闭连接
connection.close()
if __name__ == '__main__':
app.run()
```
在这个示例中,`Flask`库用于创建应用程序,并通过`render_template`函数将结果呈现为HTML模板。然后,使用`pymysql`库连接到数据库,并在路由中执行查询并返回结果。