Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to insert rows with NULL values using prepared statements? #41

Closed
amellnik opened this issue Apr 12, 2016 · 1 comment · Fixed by #42
Closed

How to insert rows with NULL values using prepared statements? #41

amellnik opened this issue Apr 12, 2016 · 1 comment · Fixed by #42

Comments

@amellnik
Copy link
Contributor

I can't figure this out for the life of me, and as far as I can tell it doesn't occur in the tests. Say for example that I have a table called "test" with two columns, "nums" and "letters". I can prepare a statement like

nums = collect(1:3)
letters = @data ["A", NA, "C"]
test = DataFrame(nums=nums, letters=letters)
statement = "REPLACE INTO test (nums,letters) values (?,?);"
sqlTypes = UInt32[MYSQL_TYPE_LONG,MYSQL_TYPE_VARCHAR]
mysql_stmt_prepare(conn,  statement)

but then I can't execute on each row like shown on the docs -- I've tried setting the NA item in the tuple to DataFrame's NA, nothing and Nullable{UTF8String}() with things like

for r in eachrow(test)
    try
        mysql_execute(conn, sqlTypes, tuple([isna(r[c]) ? nothing : r[c] for c in names(r)]...))
    catch err
        println(tuple([r[c] for c in names(r)]...), " - ", err, " - ")
    end
end

and

values = [(1, "A"), (2, Nullable{UTF8String}())]
for val in values
    mysql_execute(conn, sqlTypes, val)
end

but none of these work. What's the recommended way of doing this?

@amellnik
Copy link
Contributor Author

After more digging I realized I needed to specify the type as MYSQL_TYPE_NULL and also pass the value as a AbstractString "NULL":

for r in eachrow(test)
    try
        mysql_execute(conn, [isna(r[c]) ? MYSQL_TYPE_NULL : t for (t, c) in zip(sqlTypes, names(r))],
            tuple([isna(r[c]) ? "NULL" : r[c] for c in names(r)]...))
    catch err
        println(tuple([r[c] for c in names(r)]...), " - ", err, " - ")
    end
end

I think I can spare others a similar pain in the neck by adding a check for nothings, nullables and NAs in mysql_bind_array. I'll leave this open pending that pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant