将图像保存在Blob字段FMDB中

Kev*_*tho 2 sqlite fmdb ios swift

我已经阅读了很多教程,但是无法将图像保存到sql表中。我正在使用FMDB框架连接我的swift应用程序和sqlite数据库。这是数据库

CREATE TABLE "PRODUCTO" (
    `CODIGOPRODUCTO`    integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    `CODIGOCATEGORIA`   integer NOT NULL,
    `NOMBREPRODUCTO`    varchar(50) NOT NULL,
    `DESCRIPCIONPRODUCTO`   varchar(50) NOT NULL,
    `IMAGEN`    BLOB,
    FOREIGN KEY(`CODIGOCATEGORIA`) REFERENCES `CATEGORIA`(`CODIGOCATEGORIA`)
) 
Run Code Online (Sandbox Code Playgroud)

这是创建和保存对象的方法

let newPr: Producto = Producto()
newPr.nombre = txtNombre.text!
newPr.descripcion = txtDescripcion.text!
newPr.idCategoria = Int(categoriaSel.id)
newPr.imagen = imageView.image!
Producto().insertar(itemProducto: newPr)
Run Code Online (Sandbox Code Playgroud)

最后,这是函数“ insertar”中使用的sql语句

conexion.database!.open()
        let consulta: Bool = conexion.database!.executeUpdate("insert into PRODUCTO (CODIGOCATEGORIA,NOMBREPRODUCTO,DESCRIPCIONPRODUCTO, IMAGEN) values (\(itemProducto.idCategoria),'\(itemProducto.nombre)','\(itemProducto.descripcion)', \(UIImagePNGRepresentation(itemProducto.imagen)! as NSData))", withArgumentsIn: nil)
        conexion.database!.close()
Run Code Online (Sandbox Code Playgroud)

但是此代码始终失败。

Rob*_*Rob 5

插入Blob时,不能使用字符串插值来构建SQL。(实际上,无论如何,您实际上都不应该在SQL语句中插入值。)您应该?在SQL中使用占位符,然后将这些值作为参数传递给executeUpdate

do {
    try conexion.database!.executeUpdate("insert into PRODUCTO (CODIGOCATEGORIA,NOMBREPRODUCTO,DESCRIPCIONPRODUCTO, IMAGEN) values (?, ?, ?, ?)", values: [itemProducto.idCategoria, itemProducto.nombre, itemProducto.descripcion, UIImagePNGRepresentation(itemProducto.imagen)!])
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)