当前位置: 首页 > 工具软件 > SQLiteDB > 使用案例 >

SQLiteDB 数据库连接

韦锦程
2023-12-01
BOOL CSqliteDB::InitDB( WCHAR* pDbName, BOOL bType )
{
    //数据库信息
    m_pDbFileName = pDbName;

    //初始化数据库
    if( m_bInit )
    {
    	CloseDatabase();
    }

    //判断数据库文件是否存在
    if( !PathFileExists( m_pDbFileName ) && !CreateDatabase( m_pDbFileName ) )
    {
    	//FS_LOG_ERROR( _T( "数据库文件丢失,并且创建失败,错误码: [%d]" ), 0x00003 );
    	return FALSE;
    }

    //连接到数据
    if( !OpenDatabase( bType ) )
    {
    	//FS_LOG_ERROR( _T( "连接到数据库失败,错误码: [%d]" ), 0x00004 );
    	return FALSE;
    }

    //输入密钥,如果无密码则加密,如果有密码则解密
    //EnterEncryptKey( DB_ENCRYPT_KEY, strlen( DB_ENCRYPT_KEY ) );

    //登录信息 
    if( !IsTableExist( TABLE_NAME ) && bType )
    {
    	_CreateTable();
    }
}
BOOL CDBBase::CloseDatabase()
{
    m_bInit = false;
    if (m_pDB == nullptr) return true;

    sqlite3_finalize(m_statement);
    int ret = CloseDBHandle();

    m_statement = nullptr; 
    m_pDB = nullptr; 
    
    return (SQLITE_OK == ret);
 }

 int CDBBase::CloseDBHandle()
 {
    int code = sqlite3_close( m_pDB );
    while ( SQLITE_BUSY == code )
    {
        code = SQLITE_OK; sqlite3_stmt * stmt = sqlite3_next_stmt( m_pDB, NULL );
        if ( stmt == nullptr ) break; 
        code = sqlite3_finalize( stmt );
        if ( code == SQLITE_OK )
        {
            code = sqlite3_close( m_pDB );
        }
    }
		
    if ( SQLITE_OK != code )
    {
        m_nLastError = code;
    }
    return code;
}
BOOL CDBBase::CreateDatabase( WCHAR* pFilePullPath )
{
    if( PathFileExists( pFilePullPath ) )
    {
        return TRUE;
    }

    return CreateFileEx( pFilePullPath );
}

BOOL CDBBase::CreateFileEx( WCHAR* pFileFullPath )
{
    //要创建文件首先要检查路径存在否
    int nIndex = -1;

    WCHAR *p = _tcsrchr( pFileFullPath, _T( '\\' ) );
    if( p == nullptr )
    {
        return FALSE;
    }
    //最后创建文件
    HANDLE handle = CreateFile( pFileFullPath, GENERIC_READ | GENERIC_WRITE, 
                    FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 );
    if( handle == INVALID_HANDLE_VALUE )
    {
         return FALSE;
    }

    CloseHandle( handle );

    return true;
}
BOOL CDBBase::OpenDatabase( BOOL bType )
{
    if( m_bInit && m_pDB == NULL )	return FALSE;
    if( m_bInit && m_pDB )	return TRUE;

    CHAR szName[FS_MAX_PATH] = { 0 };
#ifdef _UNICODE
    int len = WBASELIB::ConvertUnicodeToUtf8( m_pDbFileName, szName, FS_MAX_PATH );
#endif
    if( len != 0 )
    {
        int nRet = 0;
        if( bType )	
            nRet = sqlite3_open( szName, &m_pDB );
        else
            nRet = sqlite3_open( ":memory:", &m_pDB );
        if( nRet != SQLITE_OK )
        {
            m_nLastError = nRet;
            m_pDB = NULL;
            return FALSE;
        }
    }
    else 
        return FALSE;

    m_bInit = true;
    return TRUE;
}
BOOL CDBBase::EnterEncryptKey( const char* key, int len )
{
    //sqlite3_key( m_pDB, key, len );

    return TRUE;
}

 

 类似资料: