【问题标题】:export tuple from pandas to sql将元组从熊猫导出到 sql
【发布时间】:2020-09-09 14:19:18
【问题描述】:

我在 jupyter notebook 中工作,我想将一个元组导出到 sql(在 where 条件下)。但是 id 不起作用。

numb = ('1','2', '3')


query =  """ SELECT *
              from table
              where table.number in numb """

conn = psycopg2.connect(dbname='dbname', user='user', 
                        password='pass', host='host' ,port ='port')

但是这行得通

query =  """ SELECT *
              from table
              where table.number in ('1','2', '3') """

conn = psycopg2.connect(dbname='dbname', user='user', 
                        password='pass', host='host' ,port ='port')

【问题讨论】:

    标签: python sql postgresql jupyter-notebook psycopg2


    【解决方案1】:

    你错过了它,下面的代码应该可以工作:

    numb = ('1','2', '3')
    
    
    query =  f""" SELECT *
                  from table
                  where table.number in {numb} """
    
    conn = psycopg2.connect(dbname='dbname', user='user', 
                            password='pass', host='host' ,port ='port')
    

    numb = ('1','2', '3')
    
    
    query =  """ SELECT *
                  from table
                  where table.number in {} """.format(numb)
    
    conn = psycopg2.connect(dbname='dbname', user='user',
                            password='pass', host='host' ,port ='port')
    

    print(query)的输出:

     SELECT *
                  from table
                  where table.number in ('1', '2', '3') 
    

    请注意,还有其他几种方法。你需要看pythonstring formatting

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2018-01-21
      • 2020-10-17
      • 2018-09-30
      • 1970-01-01
      相关资源
      最近更新 更多