example_03.bmx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. ' Using a prepared insert and prepared selects
  2. SuperStrict
  3. Framework BaH.DBSQLite
  4. Import BRL.filesystem
  5. Import BRL.StandardIO
  6. ' delete the db file if it already exists (just to tidy up the examples!)
  7. DeleteFile("maxtest.db")
  8. ' load the database driver, creating and opening the database
  9. Local db:TDBConnection = LoadDatabase("SQLITE", "maxtest.db")
  10. If Not db Then
  11. Print "No valid driver!"
  12. End
  13. End If
  14. ' check for errors
  15. If db.hasError() Then
  16. errorAndClose(db)
  17. End If
  18. ' if the connection is open, do something with it...
  19. If db.isOpen() Then
  20. Local names:String[][] = [ ..
  21. [ "Alfred", "Aho" ], ..
  22. [ "Brian", "Kernighan" ], ..
  23. [ "Peter", "Weinberger" ] ]
  24. ' Create a new table
  25. Local s:String = "CREATE TABLE person (id integer primary key AUTOINCREMENT, " + ..
  26. " forename varchar(30)," + ..
  27. " surname varchar(30) )"
  28. ' execute the SQL
  29. db.executeQuery(s)
  30. If db.hasError() Then
  31. errorAndClose(db)
  32. End If
  33. ' get a new query object
  34. Local query:TDatabaseQuery = TDatabaseQuery.Create(db)
  35. ' prepare the insert statement
  36. ' by preparing it once, the database can reuse it on succesive inserts which is more efficient.
  37. query.prepare("INSERT INTO person values (NULL, ?, ?)")
  38. If db.hasError() Then
  39. errorAndClose(db)
  40. End If
  41. ' iterate overy the array inserting new entries
  42. For Local i:Int = 0 Until names.length
  43. query.setString(0, names[i][0])
  44. query.setString(1, names[i][1])
  45. ' execute the prepared statement with the bound values
  46. query.execute()
  47. If db.hasError() Then
  48. errorAndClose(db)
  49. End If
  50. Next
  51. ' retrieve data from the database
  52. query.prepare("SELECT * from person WHERE surname LIKE ?")
  53. If db.hasError() Then
  54. errorAndClose(db)
  55. End If
  56. ' bind the value
  57. query.addString("%n%")
  58. ' execute the prepared query
  59. query.execute()
  60. ' iterate over the retrieved rows
  61. For Local record:TQueryRecord = EachIn query
  62. Print "Name = " + record.value(1).getString() + " " + record.value(2).getString()
  63. Next
  64. ' close the connection!
  65. db.close()
  66. End If
  67. Function errorAndClose(db:TDBConnection)
  68. Print db.error().toString()
  69. db.close()
  70. End
  71. End Function