请优化以下python查询mysql代码sql = "select id,name_xiangmu,nr from luzhi_jilu_xijie where id=82" co.to_sql(sql) jg = cs.fetchall() mb = [] for j in jg: sql = "select * from xiangmu_biaozhun where name_xiangmu='{}' and jiaose_single='检查'".format(j[1]) co.to_sql(sql) x = cs.fetchone() mb.append([j[0],j[1],j[2],x[0]])
时间: 2024-03-02 10:53:46 浏览: 90
同样的,我们可以通过 SQL JOIN 操作将两个查询合并为一个查询,避免了多次访问数据库的开销。此外,我们也需要使用参数化查询来防止 SQL 注入攻击,并且使用数据库连接池来管理数据库连接。下面是优化后的代码示例:
```python
import pymysql
from pymysql.cursors import DictCursor
from dbutils.pooled_db import PooledDB
pool = PooledDB(pymysql, maxconnections=5, host='localhost', user='root', password='password', database='database')
def query_data(id):
sql = """
SELECT j.id, j.name_xiangmu, j.nr, x.xiangmu_biaozhun
FROM luzhi_jilu_xijie j
LEFT JOIN xiangmu_biaozhun x ON j.name_xiangmu = x.name_xiangmu
WHERE j.id = %s AND x.jiaose_single = '检查'
"""
conn = pool.connection()
cursor = conn.cursor(DictCursor)
cursor.execute(sql, (id,))
result = cursor.fetchall()
cursor.close()
conn.close()
return result
```
同样地,调用 `query_data(id)` 函数即可查询数据,函数会返回一个包含查询结果的字典数组。可以根据需要进一步处理数据。
阅读全文
相关推荐

















