Check the return value of
masterdb.OpenEx(_T("DRIVER=SQL Server;DATABASE=master;SERVER=(local)\\SQLEXPRESS"));
database connection may not be success.
do perform the database operation only when database open is success. also its always good to put these code under try catch block.