MCPcopy Create free account
hub / github.com/davisking/dlib / main

Function main

examples/sqlite_ex.cpp:33–133  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

31// ----------------------------------------------------------------------------------------
32
33int 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);

Callers

nothing calls this directly

Calls 8

table_existsFunction · 0.85
execMethod · 0.80
bindMethod · 0.80
get_columnMethod · 0.80
commitMethod · 0.80
randmFunction · 0.50
move_nextMethod · 0.45
whatMethod · 0.45

Tested by

no test coverage detected