How to insert a NULL value in SQL

Rust doesn't have NULL, but SQL does. In the postgres driver, what do I need to pass to insert a NULL value in the table? I've tried with &None and that's not it, and the documentation is silent on this question (it explains Option as what you get from SQL, but not what to put)

1 Like

What crate are you using?

Rust doesn't have NULL, but it has None.
You should read the book because it seems, that you haven't discovered that topic yet.
You then also should look at Result, when you're at it.

OP explicitly stated that they tried to use None as a standin, and it didn't work? That advice doesn't really help with SQL NULLs.

3 Likes

Option<T> implements FromSql where T: FromSql and ToSql where T: ToSql , and represents nullable Postgres values.


client.simple_query("
    CREATE TABLE person (
        id      SERIAL PRIMARY KEY,
        name    TEXT NOT NULL,
        data    BYTEA
    )
")?;

let name = "Ferris";
let data = None::<&[u8]>;
client.execute(
    "INSERT INTO person (name, data) VALUES ($1, $2)",
    &[&name, &data],
)?;

sorry but I don't see how this is not very good to find. I didn't need 30 seconds for this.

The standard postgres crate. My full set is:

[dependencies]
postgres = "0.15"
dotenv = "0.9.0"
rand = "0.6.5"
1 Like

Probably because I was looking at the 0.15 documentation, which is the version I'm using, and it doesn't contain that example:

Thanks for the answer anyways, this is what I was looking for.

Fair, but even there is an example with None as well.

conn.execute("CREATE TABLE person (
                    id              SERIAL PRIMARY KEY,
                    name            VARCHAR NOT NULL,
                    data            BYTEA
                  )", &[]).unwrap();
    let me = Person {
        id: 0,
        name: "Steven".to_owned(),
        data: None
    };
    conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
                 &[&me.name, &me.data]).unwrap();

Look at the very top of the documentation, there's a button called "Go to latest version" :wink:

I did not meant to sound harsh, sorry for that.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.