| 31 | // ---------------------------------------------------------------------------------------- |
| 32 | |
| 33 | int main() try |
| 34 | { |
| 35 | // Open the SQLite database in the stuff.db file (or create an empty database in |
| 36 | // stuff.db if it doesn't exist). |
| 37 | database db("stuff.db"); |
| 38 | |
| 39 | // Create a people table that records a person's name, age, and their "data". |
| 40 | if (!table_exists(db,"people")) |
| 41 | db.exec("create table people (name, age, data)"); |
| 42 | |
| 43 | |
| 44 | // Now let's add some data to this table. We can do this by making a statement object |
| 45 | // as shown. Here we use the special ? character to indicate bindable arguments and |
| 46 | // below we will use st.bind() statements to populate those fields with values. |
| 47 | statement st(db, "insert into people VALUES(?,?,?)"); |
| 48 | |
| 49 | // The data for Davis |
| 50 | string name = "Davis"; |
| 51 | int age = 32; |
| 52 | matrix<double> m = randm(3,3); // some random "data" for Davis |
| 53 | |
| 54 | // You can bind any of the built in scalar types (e.g. int, float) or std::string and |
| 55 | // they will go into the table as the appropriate SQL types (e.g. INT, TEXT). If you |
| 56 | // try to bind any other object it will be saved as a binary blob if the type has an |
| 57 | // appropriate void serialize(const T&, std::ostream&) function defined for it. The |
| 58 | // matrix has such a serialize function (as do most dlib types) so the bind below saves |
| 59 | // the matrix as a binary blob. |
| 60 | st.bind(1, name); |
| 61 | st.bind(2, age); |
| 62 | st.bind(3, m); |
| 63 | st.exec(); // execute the SQL statement. This does the insert. |
| 64 | |
| 65 | |
| 66 | // We can reuse the statement to add more data to the database. In fact, if you have a |
| 67 | // bunch of statements to execute it is fastest if you reuse them in this manner. |
| 68 | name = "John"; |
| 69 | age = 82; |
| 70 | m = randm(2,3); |
| 71 | st.bind(1, name); |
| 72 | st.bind(2, age); |
| 73 | st.bind(3, m); |
| 74 | st.exec(); |
| 75 | |
| 76 | |
| 77 | |
| 78 | // Now lets print out all the rows in the people table. |
| 79 | statement st2(db, "select * from people"); |
| 80 | st2.exec(); |
| 81 | // Loop over all the rows obtained by executing the statement with .exec(). |
| 82 | while(st2.move_next()) |
| 83 | { |
| 84 | string name; |
| 85 | int age; |
| 86 | matrix<double> m; |
| 87 | // Analogously to bind, we can grab the columns straight into C++ types. Here the |
| 88 | // matrix is automatically deserialized by calling its deserialize() routine. |
| 89 | st2.get_column(0, name); |
| 90 | st2.get_column(1, age); |
nothing calls this directly
no test coverage detected