postgreSQL根据表字段生成insert语句

select concat('insert into XX_TABLE(', string_agg(c.attname, ','),
              ') values ('
    , string_agg(c.palce, ','),
    ')'
    , ' on conflict (pk_name)  do update set ( ',string_agg(c.attname, ','),')','=(',string_agg(c.f, ','),')') as sql
from (select 1 as fl, attname, '?' as palce, concat('EXCLUDED.',attname) as f
      from pg_attribute
      where attrelid = 'XX_TABLE'::regclass
        and attnum > 0
      order by attnum) c
group by c.fl

我这里写成了upsert, 不要的话,拿过去改改

  • 里面的XX_TABLE 替换成表名
  • pk_name 换成pk
  • ‘XX_TABLE’::regclass 这里用到了类型转换,其实你也可以去pg_table里面关联查询

附加:

jdbc 插入字段为null, 报空指针异常解决
第一种:判断出属性为null, preparedStatement.setNull(index, param)
第二种: preparedStatement.setObject(index, param)

你可能感兴趣的:(sql,java,postgresql,数据库,sql)