pymysql.connect的使用方法与结果展示
时间: 2023-06-15 19:08:09 浏览: 60
`pymysql.connect` 是 Python 操作 MySQL 数据库的一个库,可以用来连接 MySQL 数据库并执行 SQL 语句。以下是 `pymysql.connect` 的使用方法和结果展示:
```python
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 创建游标
cur = conn.cursor()
# 执行查询语句
cur.execute('SELECT * FROM students')
# 获取查询结果
results = cur.fetchall()
# 打印查询结果
for row in results:
print(f"ID: {row[0]} Name: {row[1]} Age: {row[2]}")
# 关闭游标和连接
cur.close()
conn.close()
```
以上代码中,我们首先使用 `pymysql.connect` 建立连接,参数包括主机名、端口号、用户名、密码和要连接的数据库名。然后使用 `conn.cursor()` 创建游标,执行 SQL 查询语句,获取查询结果并遍历输出。最后关闭游标和连接。
结果展示如下:
```
ID: 1 Name: Alice Age: 20
ID: 2 Name: Bob Age: 21
ID: 3 Name: Charlie Age: 22
```
相关问题
raise err.Error("Already closed") pymysql.err.Error: Already closed raise err.Error("Already closed") pymysql.err.Error: Already closed
这个错误通常是因为在已经关闭的数据库连接上尝试执行操作导致的。请确保你的数据库连接是在执行查询或其他操作之前正确打开的,并且没有被意外关闭。
以下是一个示例代码,展示了如何正确使用 pymysql 库来执行查询:
```python
import pymysql
# 建立数据库连接
connection = pymysql.connect(
host='localhost',
user='username',
password='password',
database='database_name'
)
try:
# 创建游标对象
cursor = connection.cursor()
# 执行查询操作
sql = "SELECT * FROM table_name"
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
for row in result:
print(row)
finally:
# 关闭游标和数据库连接
cursor.close()
connection.close()
```
请确保在 `finally` 代码块中关闭游标和连接,即使发生异常也能正常关闭数据库连接。
如果问题仍然存在,请检查你的代码是否正确打开和关闭数据库连接,并确保不会重复关闭已关闭的连接。此外,确保你的数据库服务器正在运行,并且你的用户名和密码是正确的。如果问题仍然无法解决,请检查你的数据库服务器日志以获取更多详细信息。
def show_query1_result(self): # 查询数据 db = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', db='jj_tset') cursor = db.cursor() db_sql = """ """ cursor.execute(db_sql) result = cursor.fetchall() db.close() # 清空表格 self.query1_window.table_widget.setRowCount(0) self.query1_window.table_widget.setColumnCount(len(result[0])) # 添加数据到表格 for row_num, row_data in enumerate(result): self.query1_window.table_widget.insertRow(row_num) for col_num, col_data in enumerate(row_data): self.query1_window.table_widget.setItem(row_num, col_num, QTableWidgetItem(str(col_data))) # 显示窗口 self.query1_window.show()数据展示页面怎么设置筛选器按ID筛选结果并展示
你可以添加一个筛选器控件,例如QComboBox,让用户选择要按哪个字段进行筛选。然后在查询按钮的槽函数中,根据用户选择的字段构建SQL语句,再执行查询操作,并将结果展示在表格中。
以下是示例代码:
```python
from PyQt5.QtWidgets import QComboBox
class Query1Window(QWidget):
def __init__(self):
super().__init__()
self.table_widget = QTableWidget(self)
self.filter_combo = QComboBox(self)
self.filter_combo.addItems(['ID', 'Name', 'Age']) # 添加筛选器选项
self.query_btn = QPushButton('Query', self)
self.query_btn.clicked.connect(self.show_result)
def show_result(self):
# 获取用户选择的筛选字段和筛选值
filter_field = self.filter_combo.currentText()
filter_value = self.filter_line_edit.text()
# 构建SQL语句
db_sql = f"SELECT * FROM jj_tset WHERE {filter_field}='{filter_value}'"
# 执行查询操作
db = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', db='jj_tset')
cursor = db.cursor()
cursor.execute(db_sql)
result = cursor.fetchall()
db.close()
# 清空表格
self.table_widget.setRowCount(0)
self.table_widget.setColumnCount(len(result[0]))
# 添加数据到表格
for row_num, row_data in enumerate(result):
self.table_widget.insertRow(row_num)
for col_num, col_data in enumerate(row_data):
self.table_widget.setItem(row_num, col_num, QTableWidgetItem(str(col_data)))
# 显示窗口
self.show()
```
需要注意的是,上述代码并没有添加筛选值的输入控件,你可以根据需要自行添加。另外,由于SQL注入等安全问题,建议使用参数化查询来构建SQL语句。