dqs13465424392 2015-10-04 07:46
浏览 31
已采纳

postgresql不喜欢多个逗号

I'm working with a php script that compiles data into insert statements for a postgresql database. It was originally written for a mysql database, so there are, of course, some differences.

One thing I've run into that I can't seem to figure out, is postgresql not liking this type of statement:

INSERT INTO table ( col1, col2, col3, col4 ) VALUES ( 'value',,'value','value' );

Any time there's a missing value, the query errs at the point of the double commas.

Any ideas on how to bypass this? The fields all have varying datatypes so using a '' as a filler fails if the col is expecting an int.

  • 写回答

1条回答 默认 最新

  • douliexing2195 2015-10-04 07:51
    关注

    PostgreSQL is following the SQL standard here. Your statement is invalid, so it produces an error.

    You must either:

    • Dynamically generate the column-name list to include only columns you want to set; or
    • Use the keyword DEFAULT to say "do whatever you'd do if I hadn't specified this column"

      e.g

      INSERT INTO table ( col1, col2, col3, col4 )
      VALUES ( 'value',DEFAULT,'value','value' );
      

    Note that the DEFAULT keyword is not quoted. It isn't an identifier or a literal. It's a keyword and must be unquoted. This means you cannot pass it as a query parameter via most parameterized statement query interfaces.

    That means that either way, you're stuck with dynamic SQL.

    I think this is a real flaw in most SQL client interfaces, which should provide a generic object you can pass to specify "make this column a default field", or a setDefault(paramname) method, or similar. Unfortunately, that won't help you, because most of them don't do it.

    You can pass NULL as the placeholder if the column is nullable, but this is not the same thing as passing DEFAULT. If you use the DEFAULT keyword then any DEFAULT expression on the column is used, as if you hadn't specified the column at all. If you use NULL, any DEFAULT expression on the column definition is overridden and ignored.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable