For instance, how to execute the equivalent following SQL (which inserts into a BINARY(16) field)
INSERT INTO Table1 (MD5) VALUES (X'6717f2823d3202449201145073ab871A'),(X'6717f2823d3202449301145073ab371A')
using dbWriteTable()? Doing
dbWriteTable(db, "Table1", data.frame(MD5 = "X'6717f2823d3202449201145073ab871A'", ...), append = T, row.names = F)
doesn't seem to work - it writes the values as text.
In the end, I'm going to have a big data.frame of hashes that I want to write, and so perfect for using dbWriteTable. But I just can't figure out how to INSERT the data.frame into binary database fields.
So here are two possibilities that seem to work. The first uses
dbSendQuery(...)in a loop (you've probably thought of this already...).If your data frame of hashes is very large, then
df.WriteFast(...)does the same thing asdb.WriteTable(...)only it should be faster.Note that
result.1is a data frame, and if we use it in a call todbWriteTable(...)we can successfully write the hashes to a BLOB. So it is possible.The second approach takes advantage of R's
rawdata type to create a data frame structured likeresult.1, and passes that todbWriteTable(...). You'd think this would be easy, but no.In this approach, we create a data frame
df.rawwhich has one column,MD5, wherein each element is a list of raw bytes. The utility functionh2r(...)takes a character representation of the hash, breaks it into a vector ofchar(2)(the bytes), then interprets each of those as hex (as.hexmode(...)), converts the result to raw (as.raw(...)), and finally returns the result as a list.Vectorize(...)is a wrapper that allowshash2raw(...)to take a vector as its argument.Personally, I think you're better off using the first approach: it takes advantage of SQLite's internal mechanism for writing hex to BLOBs, and it's much easier to understand.