【问题标题】:Using python to change and run SQL queries使用 python 更改和运行 SQL 查询
【发布时间】:2019-01-22 12:02:53
【问题描述】:

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

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_ids添加到SQL查询并通过python运行并将其保存到csv文件?

【问题讨论】:

    标签: python sql dataframe automation


    【解决方案1】:

    要将数据放入字符串中,可以使用 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 模块。如PyMySQL 用于连接 MySQL 数据库。 https://pypi.org/project/PyMySQL/

    不过,您可以使用诸如 peeweeSqlAlchemy 之类的 ORM 来让您在处理 SQL 数据库时更轻松一些。 Pandas 和 SqlAlchemy 混合得非常好。但是 Peewee 更容易上手。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2011-06-04
      • 2018-11-11
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多