Postgresql: using 'NULL' value when insert and update rows with prepared statements

自闭症网瘾萝莉.ら 提交于 2019-12-18 08:55:02

问题


sometimes i need to insert into the table some null values, or update them setting the value to NULL.

I've read somewhere in the postgresql documentation that this cant be done, but can be tricket with the default value:

pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)

p.s: i know that in this example i'll have the same result with

pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')

But the problems comes witht the prepared statements:

pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, default)");
pg_exec($pgconn, 'insert_null_val', array('whatever'));
//this works, but
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', 'NULL'));
//insert into the table the string 'NULL'.
//instead using array('whatever', '') it assume the col_b as empty value, not NULL.

The same problem comes with the update query.

I think there is a solution, becose pgmyadmin can do that (or seem like it can), and is written i php (i dont think it doesnt use the prepared statements anyway)

If youre wondering why i need to paly with null values in my tables, let me throw an example (maybe there is a way better then the null value): assume i have the user table, and the email col: this one can be empty, but is a unique index.. 2 empty email are equal and violates the unique constraint, while 2 NULL values are not equal and can coexist.


回答1:


Use the php's literal NULL as a parameter:

pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', NULL));


来源:https://stackoverflow.com/questions/1027499/postgresql-using-null-value-when-insert-and-update-rows-with-prepared-stateme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!