blob_test.bmx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. SuperStrict
  2. Framework Database.PostgreSQL
  3. Import BRL.filesystem
  4. Import BRL.RamStream
  5. Import BRL.JPGLoader
  6. Import BRL.StandardIO
  7. Local db:TDBConnection = LoadDatabase("POSTGRESQL", "maxtest", "localhost", 0, "user", "pass")
  8. If Not db Then
  9. Print "Didn't work..."
  10. End
  11. End If
  12. If db.hasError() Then
  13. errorAndClose(db)
  14. End If
  15. Local names:String[][] = [ ..
  16. [ "Alfred", "Aho", "alfred-aho.jpg" ], ..
  17. [ "Brian", "Kernighan", "brian-kernighan.jpg" ], ..
  18. [ "Peter", "Weinberger", "pjw.jpg" ] ]
  19. If db.isOpen() Then
  20. db.executeQuery("DROP TABLE person")
  21. db.executeQuery("DROP SEQUENCE person_id")
  22. ' create the auto-incrementing field
  23. db.executeQuery("CREATE SEQUENCE person_id INCREMENT 1 START 1")
  24. Local s:String = "CREATE TABLE person (id integer primary key DEFAULT NEXTVAL('person_id'), " + ..
  25. " forename varchar(30)," + ..
  26. " surname varchar(30), image bytea )"
  27. db.executeQuery(s)
  28. If db.hasError() Then
  29. errorAndClose(db)
  30. End If
  31. ' get a new query object
  32. Local query:TDatabaseQuery = TDatabaseQuery.Create(db)
  33. ' prepare the insert statement
  34. ' by preparing it once, the database can reuse it on succesive inserts which is more efficient.
  35. query.prepare("INSERT INTO person (forename, surname, image) values ($1, $2, $3)")
  36. If db.hasError() Then
  37. errorAndClose(db)
  38. End If
  39. ' iterate round the array inserting new entries
  40. For Local i:Int = 0 Until 3
  41. query.bindValue(0, TDBString.Set(names[i][0]))
  42. query.bindValue(1, TDBString.Set(names[i][1]))
  43. ' load some data (raw jpg data)
  44. Local b:Byte[] = LoadByteArray("images/" + names[i][2])
  45. ' bind it (copying the data)
  46. query.bindValue(2, TDBBlob.Set(b, b.length))
  47. query.execute()
  48. If db.hasError() Then
  49. errorAndClose(db)
  50. End If
  51. Next
  52. query = db.executeQuery("SELECT * from person")
  53. If db.hasError() Then
  54. errorAndClose(db)
  55. End If
  56. While query.nextRow()
  57. Local record:TQueryRecord = query.rowRecord()
  58. Print (record.GetInt(0) + ". Name = " + record.GetString(1) + " " + record.GetString(2))
  59. ' get the blob data
  60. Local b:TDBBlob = TDBBlob(record.value(3))
  61. ' create a pixmap (from the raw jpg data)
  62. Local pix:TPixmap = LoadPixmap(CreateRamStream(b.getBlob(), b.size(), True, False))
  63. If pix Then
  64. Print "Dimension = " + pix.width + ", " + pix.height
  65. End If
  66. Wend
  67. db.close()
  68. End If
  69. Function errorAndClose(db:TDBConnection)
  70. Print db.error().toString()
  71. db.close()
  72. End
  73. End Function