example_02.bmx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. ' Using a prepared statement
  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.bindValue(0, TDBString.Set(names[i][0]))
  44. query.bindValue(1, TDBString.Set(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 = db.executeQuery("SELECT * from person")
  53. If db.hasError() Then
  54. errorAndClose(db)
  55. End If
  56. ' iterate over the retrieved rows
  57. While query.nextRow()
  58. Local record:TQueryRecord = query.rowRecord()
  59. Print "Name = " + record.value(1).getString() + " " + record.value(2).getString()
  60. Wend
  61. ' close the connection!
  62. db.close()
  63. End If
  64. Function errorAndClose(db:TDBConnection)
  65. Print db.error().toString()
  66. db.close()
  67. End
  68. End Function