Search This Blog

Monday, July 20, 2009

VC++ code to copy/move records from one database in to another database having the same table.

Download Library and header files from below link:
http://www.codeproject.com/KB/database/CppSQLite.aspx



int CopyMoveDBTable( LPCTSTR lpcSourceDBPath ,LPCTSTR lpcSourceTable , LPCTSTR lpcTargetDBPath ,LPCTSTR lpcTargetTable ,LPCTSTR lpcCriteria ,BOOL bCopy)
{

     CppSQLite3DB* m_db;    
     try
     {
          CString csQuery;              
          m_db=new CppSQLite3DB();         
          m_db->open(lpcSourceDBPath);          
         
          csQuery.Format( "Attach '%s' as sourcedbTable;",lpcTargetDBPath);
          m_db->execDML(csQuery);
          m_db->execDML("begin transaction");
          csQuery.Format( "insert into sourcedbTable.%s select * from main.%s %s ;",lpcSourceTable,lpcTargetTable,lpcCriteria);
          m_db->execDML("commit transaction");
          //insert into sourcedbTable.emptable select * from main.embdb where empid < 1 ;");
          m_db->execDML(csQuery);
          if(bCopy==FALSE)
          {
               m_db->execDML("begin transaction");
               csQuery.Format( "delete from main.%s %s ;",lpcSourceTable,lpcCriteria);
               m_db->execDML(csQuery);
               m_db->execDML("commit transaction");
          }
          csQuery.Format( "DETACH sourcedbTable;");
          m_db->execDML(csQuery);
         
          m_db->close();         
     }

     catch (CppSQLite3Exception& e)
     {
          delete m_db;
         
          AfxMessageBox( e.errorMessage());
          return -1;
     }
     delete m_db;
    
     return 1;

}    

EXample:

     CString csDBPath,csMirrorDB,csTable,csCriteria;
     BOOL bCopy=FALSE;
     csDBPath= "c:\\DatabaseSqlite\\Employee.db";
     csMirrorDB= "c:\\DatabaseSqlite\\Employeemirror.db";
     csTable="EmpTable";
     csCriteria="where empId>5";
     CopyMoveDBTable( csDBPath,csTable, csMirrorDB ,csTable ,csCriteria ,bCopy);

No comments: