簡體   English   中英

如何根據numpy數據類型確定PostgreSQL列數據類型?

[英]How to determine PostgreSQL column data type based on numpy data types?

在Python方面,我有一個信號列表,每個信號都是一個numpy.ndarray

numpy.uint8變化的信號中 - 包括numpy.uint8numpy.uint16numpy.uint32numpy.float64numpy.bytes_

最后我想將信號傳遞給PostgreSQL中的一個表,每個信號都是一列。 我現在停留在ADD COLUMN步驟,因為需要為PostgreSQL中的每一列指定數據類型。

當我使用psycopg2作為適配器時,我在文檔中找到了這個表 ,但沒有找到任何信息來幫助以動態方式添加具有適當數據類型的列。

我的想法/方法是 - 考慮到我所擁有的信號中只有5個已知的dtype,我可以:

  1. 迭代信號列表
  2. 獲取每個信號的第一個元素,找到它的dtype
  3. 確定每個信號的相應PostgreSQL數據類型
  4. 生成相應的PostgreSQL數據類型列表
  5. 添加列時使用生成的列表傳遞數據類型

我不確定這是否是最佳方式。 是否有現有的lib可以完成這項工作? 或者有更好的方法來編碼這種方法嗎?

感謝您的任何見解!

它根本不優雅,但最后我使用了這種方法:

讀取每個信號中第一個元素的type()並將其轉換為str ,稍后將其傳遞給函數以基本匹配相應的PostgreSQL數據類型。 請注意,只涵蓋與我的項目相關的numpy數據類型。

def db_data_type(data_type):
    # Input is string of data type
    conversion_table = {
        "<class 'numpy.uint8'>":    'int2',     # 0 to 255          # -32768 to 32767
        "<class 'numpy.uint16'>":   'int4',     # 0 to 65535        # -2147483648 to 2147483647
        "<class 'numpy.uint32'>":   'int8',     # 0 to 4924967295   # -9223372036854775808 to 9223372036854775807
        "<class 'numpy.int8'>":     'int2',     # -128 to 127
        "<class 'numpy.int16'>":    'int2',     # -32768 to 32767
        "<class 'numpy.int32'>":    'int4',     # -2147483648 to 2147483647
        "<class 'numpy.float64'>":  'float8',   # double
        "<class 'numpy.bytes_'>":   'text',
    }
    return conversion_table[data_type]

基本上,當我遍歷一堆信號(數據庫表中的列)時,我將獲得一個信號名稱列表(DB中的列名稱)和數據類型列表(DB中的列數據類型)。 這是psycopg2生成SQL查詢的代碼:

def db_create_columns(conn, table, columns, types):
    cur = conn.cursor()
    for i in range(len(columns)):
        sql_add_column = psycopg2.sql.SQL("""ALTER TABLE {} ADD COLUMN {} {} ;""") \
            .format(psycopg2.sql.Identifier(table),
                    psycopg2.sql.Identifier(columns[i]),
                    psycopg2.sql.Identifier(types[i]))
        try:
            cur.execute(sql_add_column)
        except Exception as e:
            print('Error occurred when adding data column [%s].\n%s' % (columns[i], e))
    cur.close()
    conn.commit()
    return

這里的函數參數是:連接到DB,表名,列名列表,數據類型列表。

如果有更好的方法,請毫不猶豫地指出。 我很欣賞它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM