2017-04-13 102 views
2

我在postgresql中有一個名爲mytable的表格,我需要將這個表格的內容從python應用程序打印到stdout。在python中打印postgresql表格到標準輸出

我目前做如下:

 conn = psycopg2.connect("dbname=postgres user=postgres password=psswd") 
     cur = conn.cursor() 
     cur.copy_to(sys.stdout,'mytable',sep = '\t') 

不過,我得到一些「\ n」時,它的一些列之間的印刷英寸我相信之所以發生這種情況是因爲在打印過程中,該行超出並進入了psql終端的下一行,因此出現這些\ N。

輸出:

E0307 1  M  400  Ethan UTDallas  12.98580404  \N  50.79403657  1 
E0307 1  M  400  Lucas Baylor 15.18511175  \N  56.87285183  3 
E0307 1  M  400  Jackson Baylor 13.64228411  \N  56.87285183  3 
E0307 1  M  400  Jacob Baylor 13.19878974  \N  56.87285183  3 
E0307 1  M  400  Samuel Baylor 14.84666623  \N  56.87285183  3 

我的問題是:在輸出

  1. 如何擺脫這些\ n?是否有另一種打印表格的方式?我試圖避免我必須執行整個「SELECT * FROM my_table」查詢的方法。某些僅使用要打印的表格名稱的東西。

  2. 另外,如何在打印時獲取表格標題?我試過如下:

    cur.execute( 「COPY MYTABLE與CSV標題STDOUT」)

我收到此錯誤信息:

ProgrammingError: can't execute COPY TO: use the copy_to() method instead 

而且,我不知道如果這是最好的方法。但我試圖做:)

回答

0

沒有一個postgress表格方便測試這個,但爲你做這個工作?

import psycopg2 as pg 
import pandas as pd 
import pandas.io.sql as psql 

connection = pg.connect("dbname=postgres user=postgres password=psswd") 
#my_table = pd.read_sql_table('table_name', connection) 
my_table = pd.read_sql('select * from my-table-name', connection) 
another_attempt= psql.read_sql("SELECT * FROM my-table-name", connection) 

print(my_table) 

# OR 
print(another_attempt) 
+0

我得到這個錯誤: 回溯(最近通話最後一個): 文件 「」,1號線,在 MY_TABLE = pd.read_sql_table('team_totals 」,連接) 文件 「C:\用戶\ peshalnayak \ Anaconda3 \ LIB \站點包\大熊貓\ IO \ sql.py」,線351,在read_sql_table 提高NotImplementedError( 「read_sql_table只支持」 NotImplementedError :read_sql_table僅支持SQLAlchemy connectable。 – foobar

+0

好吧我會更新我的答案,使用read_sql函數,其中查詢 –

+0

好吧,希望'my_table'或'another_attempt'行工作。一個使用標準的'pd_read_sql',第二個使用'pd.io.sql',我發現它特別建議連接到postgres。好奇它是否有用,或者兩者兼而有之。 –

2

\Nnull值的默認文本表示。它可以與null parameter of copy_to

改爲在輸出頭使用copy_expert

copy = "copy mytable to stdout with csv header delimiter '\t' null 'NULL'" 
cursor.copy_expert(copy, sys.stdout) 
0

正如內託前文所述:cur.copy_expert("sql statement", sys.stdout)會工作。要使用copy_to,您需要傳遞null參數。

如果您選擇copy_to方法(設置空值 - 請參閱文檔),請嘗試此操作。首先打印列名。

header = [i[0] for i in cur.description 
print header 
cur.copy_to(sys.stdout, 'table', sep='\t', null='\N') 
相關問題