python CGI 提取表单POST的数据连接MYSQL数据库查询,并将查到的数据显示在网页上
时间: 2024-03-02 13:54:27 浏览: 30
好的,我可以帮你解答这个问题。首先,你需要在你的 Python 代码中使用 `cgi` 和 `mysql.connector` 模块来完成这个任务。
以下是一个简单的例子,可以帮助你完成这个任务:
```python
#!/usr/bin/env python
import cgi
import mysql.connector
# 连接到 MySQL 数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 获取表单数据
form = cgi.FieldStorage()
search_term = form.getvalue('search_term')
# 查询数据库
mycursor.execute("SELECT * FROM yourtable WHERE column_name = %s", (search_term,))
results = mycursor.fetchall()
# 输出查询结果到网页
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>CGI Python MySQL</title>")
print("</head>")
print("<body>")
print("<h2>Search Results:</h2>")
for row in results:
print("<p>" + row[0] + ": " + row[1] + "</p>")
print("</body>")
print("</html>")
```
在这个例子中,我们首先连接到 MySQL 数据库,并创建了一个游标对象。然后,我们从表单中获取搜索词,使用 MySQL 查询语句查询数据库,然后将结果输出到网页。
请注意,这个例子仅供参考,你需要根据你自己的需求进行修改。例如,你需要将 `yourusername`、`yourpassword` 和 `yourdatabase` 替换为你自己的 MySQL 数据库信息,同时修改查询语句和输出结果的格式。
希望这个例子可以帮助你完成任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)