如何在MFC中导出MySQL结果(选择数据)

时间:2018-12-26 07:24:49

标签: c++ mysql mfc

使用MFC执行选择查询后,我导出.csv

我通过Visual C ++ 6.0和MySQL Server 5.X使用MFC

MYSQL_RES m_res = mysql_store_result(&mysql);

我不知道如何使用m_res连接导出.csv

是否可以导出数据? 如果不是,我将在显示gridview后通过.csv导出数据。

1 个答案:

答案 0 :(得分:0)

以下是使用MFC方式(CString / CStringList,CArchive等)的示例:

    void PrintListCSV( CArchive &archiveContent, CStringList & strList, CString szSeparator ){

            if( strList.IsEmpty() )
                    return;

            CString strOneRecord;

            POSITION posTail = GetTailPosition();
            POSITION pos;

            for( pos = strList.GetHeadPosition(); pos != posTail; )
            {
                    CString str = strList.GetNext( pos );
                    strOneRecord += str;
                    strOneRecord += szSeparator;
            }

            strOneRecord += strList.GetNext( postTail );
            strOneRecord += _T("\r\n"); // windows change a line
            archiveContent.WriteString(strOneRecord);
    }


    BOOL ExportCSV( CString strFileName, MYSQL_RES * mysql_res )
    {
            CFile filePersistent;
            if( !filePersistent.Open( strFileName, CFile::modeCreate | CFile::modeWrite))
            {
                    //Error log, message box, etc.
                    return FALSE;
            }

            CArchive archiveContent( &filePersistent, CArchive::store);
            CString strSeparator(_T(";"));

            MYSQL_FIELD *field;

            //print column name - optional 
            CStringList fieldList;
            unsigned int num_fields = mysql_num_fields(mysql_res);

            while((field = mysql_fetch_field(mysql_res)) != NULL )
            {
                    fieldList.AddTail( field->name );
            }

            PrintListCSV( archiveContent, fieldList, strSeparator );

            //print each record set
            while ((row = mysql_fetch_row(mysql_res)))
            {
                    CStringList recordList;
                    for(i = 0; i < num_fields; i++)
                    {
                            recordList.AddTail( row[i] ? row[i] : "NULL" );
                    }

                    PrintListCSV( archiveContent, recordList, strSeparator );
            }

            archiveContent.Close();
            filePersistent.Close();

            return TRUE;
    }

使用方法:

    //some where in your main function ...
    //Open mysql connection, execute SQL commande ...
    // ...

    MYSQL_RES *m_res = mysql_store_result(&mysql);
    CString szFileName("C:\\SOME_PATH\\FILENAME.csv");

    if( !ExportCSV( szFileName, m_res ) ){
            //Cannot export to CSV file ...
            //Error message, log, etc.
    }

    //free the SQL result
    mysql_free_result( m_res );

    //...

警告::此代码可能包含编译器错误。希望我的记忆能为我服务。