| 1 | /////////////////////////////////////////////////////////////////////////////// |
| 2 | // |
| 3 | // Copyright (C) 2010-2011 Artyom Beilis (Tonkikh) <[email protected]> |
| 4 | // |
| 5 | // Distributed under: |
| 6 | // |
| 7 | // the Boost Software License, Version 1.0. |
| 8 | // (See accompanying file LICENSE_1_0.txt or copy at |
| 9 | // http://www.boost.org/LICENSE_1_0.txt) |
| 10 | // |
| 11 | // or (at your opinion) under: |
| 12 | // |
| 13 | // The MIT License |
| 14 | // (See accompanying file MIT.txt or a copy at |
| 15 | // http://www.opensource.org/licenses/mit-license.php) |
| 16 | // |
| 17 | /////////////////////////////////////////////////////////////////////////////// |
| 18 | #include <cppdb/frontend.h> |
| 19 | #include <iostream> |
| 20 | #include <ctime> |
| 21 | |
| 22 | |
| 23 | int main() |
| 24 | { |
| 25 | try { |
| 26 | cppdb::session sql("sqlite3:db=db.db"); |
| 27 | |
| 28 | sql << "DROP TABLE IF EXISTS test" << cppdb::exec; |
| 29 | |
| 30 | sql<< "CREATE TABLE test ( " |
| 31 | " id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " |
| 32 | " n INTEGER," |
| 33 | " f REAL, " |
| 34 | " t TIMESTAMP," |
| 35 | " name TEXT " |
| 36 | ") " << cppdb::exec; |
| 37 | |
| 38 | std::time_t now_time = std::time(0); |
| 39 | |
| 40 | std::tm now = *std::localtime(&now_time); |
| 41 | |
| 42 | cppdb::statement stat; |
| 43 | |
| 44 | stat = sql << |
| 45 | "INSERT INTO test(n,f,t,name) " |
| 46 | "VALUES(?,?,?,?)" |
| 47 | << 10 << 3.1415926565 << now <<"Hello 'World'"; |
| 48 | |
| 49 | stat.exec(); |
| 50 | std::cout<<"ID: "<<stat.last_insert_id() << std::endl; |
| 51 | std::cout<<"Affected rows "<<stat.affected()<<std::endl; |
| 52 | |
| 53 | stat.reset(); |
| 54 | |
| 55 | stat.bind(20); |
| 56 | stat.bind_null(); |
| 57 | stat.bind(now); |
| 58 | stat.bind("Hello 'World'"); |
| 59 | stat.exec(); |
| 60 | |
| 61 | |
| 62 | cppdb::result res = sql << "SELECT id,n,f,t,name FROM test"; |
| 63 | |
| 64 | while(res.next()) { |
| 65 | double f=-1; |
| 66 | int id,k; |
| 67 | std::tm atime; |
| 68 | std::string name; |
| 69 | res >> id >> k >> f >> atime >> name; |
| 70 | std::cout <<id << ' '<<k <<' '<<f<<' '<<name<<' '<<asctime(&atime)<< std::endl; |
| 71 | } |
| 72 | |
| 73 | res = sql << "SELECT n,f FROM test WHERE id=?" << 1 << cppdb::row; |
| 74 | if(!res.empty()) { |
| 75 | int n = res.get<int>("n"); |
| 76 | double f=res.get<double>(1); |
| 77 | std::cout << "The values are " << n <<" " << f << std::endl; |
| 78 | } |
| 79 | } |
| 80 | catch(std::exception const &e) { |
| 81 | std::cerr << "ERROR: " << e.what() << std::endl; |
| 82 | return 1; |
| 83 | } |
| 84 | return 0; |
| 85 | } |