Skip to main content
 首页 » 编程设计

python之使用 python 更改和运行 SQL 查询

2024年12月31日8bonelee

我有以下代码可根据用户输入创建数据框:

import pandas as pd 
  from pandas import DataFrame 
 
 publications =  
 pd.read_csv("C:/Users/nkambhal/data/pubmed_search_results_180730.csv", sep=  
 "|") 
 
 publications['title'] = publications['title'].fillna('') 
 
 search_term = input('Enter the term you are looking for: ') 
 
 publications[['title','publication_id']]  
 [publications['title'].str.contains(search_term)] 
 title_mask =  
 publications.title.str.lower().str.contains(search_term.lower()) 
 new = publications.loc[title_mask, ['title', 'publication_ID']] 

现在我想使用新数据框中的发布 ID 来运行此 SQL 查询:

SELECT 
   author_profile 
   pub_lst.*  
FROM 
   pub_lst 
JOIN 
    author_profile 
        ON pub_lst.author_id = author_profile.author_id 
WHERE 
    pub_lst.publication_id IN (67855,65559); 

在 where 语句中,我希望新数据框中的 ID 存在。所以在数据框中有 publication_ids ( 5, 6, 4) 然后我希望将它们添加到查询中。

如何将适当的 publication_id 添加到 SQL 查询并通过 python 运行它并将其保存到 csv 文件?

请您参考如下方法:

要将数据放入字符串中,可以使用 python 的 str.format 函数。你可以多读一点here

对于您的查询字符串,它应该像这样计算:

query_string = """ 
SELECT 
   author_profile 
   pub_lst.*  
FROM 
   pub_lst 
JOIN 
    author_profile 
        ON pub_lst.author_id = author_profile.author_id 
WHERE 
    pub_lst.publication_id IN {}; 
""" 
print(query_string.format(str(tuple(new.publication_ID.values)))) 

至于运行查询,您需要为要连接的任何数据库使用 python 模块。例如用于连接到 MySQL 数据库的 PyMySQL。 https://pypi.org/project/PyMySQL/

不过,您可以使用 ORM,例如 peewee或 SqlAlchemy让您在处理 SQL 数据库时的生活更轻松一些。 Pandas 和 SqlAlchemy 混合得很好。但是 Peewee 更容易上手。

要创建 csv,您可以使用内置的 python csv 模块、pandas 或 Peewee 或 SqlAlchemy按难度升序排列。