00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #include "sqlite3xx.hpp"
00030
00031
00032
00033 Sqlite3Context::Sqlite3Context( const string &dbName )
00034 : handle( 0 ),
00035 _dbName( dbName )
00036 {
00037 if( !_dbName.empty() )
00038 {
00039 try
00040 {
00041 open();
00042 }
00043 catch( SqlDatabaseOpenException &e )
00044 {
00045 throw e;
00046 }
00047 }
00048 }
00049
00050 Sqlite3Context::~Sqlite3Context()
00051 {
00052 close();
00053 }
00054
00055 void Sqlite3Context::close()
00056 {
00057 if( handle )
00058 {
00059 sqlite3_close( handle );
00060 handle = 0;
00061 }
00062 }
00063
00064 string Sqlite3Context::escapeString( const string ¶m ) const
00065 {
00066 string output= param;
00067 string::size_type pos = 0;
00068
00069 while( ( pos = output.find( "'", pos ) ) != string::npos )
00070 {
00071 output.replace( pos, 1, "''" );
00072 pos += 2;
00073 }
00074
00075 return output;
00076 }
00077
00078 string Sqlite3Context::version() const
00079 {
00080 string v = "SQLite ";
00081 v += sqlite3_libversion();
00082
00083 return v;
00084 }
00085
00086
00087
00088 void Sqlite3Context::open()
00089 {
00090 if( handle == 0 )
00091 {
00092 if( sqlite3_open( _dbName.c_str(), &handle ) )
00093 {
00094 string ex = "Failed to open database: ";
00095 ex += sqlite3_errmsg( handle );
00096 close();
00097 throw SqlDatabaseOpenException( ex );
00098 }
00099 }
00100 }
00101
00102 SqlResult Sqlite3Context::query( const string &sql ) const
00103 {
00104 sqlite3_stmt *stmt = 0;
00105 const char *tail = 0;
00106 string original = sql;
00107 SqlResult result;
00108
00109 do
00110 {
00111 if( sqlite3_prepare( handle, original.c_str(), -1, &stmt, &tail )
00112 != SQLITE_OK )
00113 {
00114 string ex = "Bad SQL statement: ";
00115 ex += original;
00116 ex += "\nSqlite3 message: ";
00117 ex += sqlite3_errmsg( handle );
00118 throw SqlDatabaseBadStatementException( ex );
00119 }
00120
00121 while( sqlite3_step( stmt ) == SQLITE_ROW )
00122 {
00123 SqlRow *row = new SqlRow( sqlite3_column_count( stmt ) );
00124 result.add( row );
00125
00126 for( int col = 0; col < row->columns(); ++col )
00127 {
00128 row->add( reinterpret_cast< const char* >
00129 ( sqlite3_column_text( stmt, col ) ) );
00130 }
00131 }
00132
00133 original = tail;
00134 }
00135 while( *tail != '\0' );
00136
00137 sqlite3_finalize( stmt );
00138 return result;
00139 }