1. 程式人生 > >C++中 MFC DLL如何連線mysql資料庫以及按條件查詢和時間的比較

C++中 MFC DLL如何連線mysql資料庫以及按條件查詢和時間的比較


1.把mysql資料庫的以上檔案複製到 “右鍵點選專案名——》在檔案資源管理器中開啟資料夾”中。

2.右鍵點選專案名——》新增——》現有項,選中從mysql複製過來的所有檔案,點選新增。

3.可以寫程式碼了。

extern "C" bool PASCAL EXPORT queryId(int numA)

{
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    // 此處為普通函式體    
    bool flag=false;
    MYSQL m_sqlCon;  
    try{  
        mysql_init(&m_sqlCon); 
        if(!mysql_real_connect(&m_sqlCon, "IP地址","登陸名","登陸密碼","資料庫名",3306,NULL,0)){  
            AfxMessageBox(_T("資料庫連線失敗!"));
        }else{
             char select_user[255];
             CString beginDate,endDate;
             int num_col;
             MYSQL_RES *result=NULL;
             MYSQL_ROW mysql_row;

             sprintf_s(select_user, "select * from gmicus where id='%d'", numA);
             if (mysql_query(&m_sqlCon, select_user) || !(result = mysql_store_result(&m_sqlCon))) {
                 AfxMessageBox(_T("程式執行錯誤!"));
              }
             num_col=(int)mysql_num_fields(result);
             if(mysql_num_rows(result)==0) {
                 AfxMessageBox(_T("未找到您的資訊!"));
             }else{
                 while (mysql_row = mysql_fetch_row(result))//獲取具體的資料
                {
                    for (int i = 0; i < num_col; i++)
                    {       
                        if(i==2){
                            beginDate=CStringW(mysql_row[i]);
                        }
                        if(i==3){
                            endDate=CStringW(mysql_row[i]);
                        }
                    }
                }
                 CTime m_time;;
                 CTime datetime;
                 datetime=CTime::GetCurrentTime();                                                                              
                 CString str2=datetime.Format("%Y-%m-%d %H:%M:%S");  
                 /*CString str;
                 str.Format(_T("%s"), str2);
                 AfxMessageBox(str);*/
                 COleDateTime begin;
                 begin.ParseDateTime( beginDate );   
                 COleDateTime end;
                 end.ParseDateTime( endDate );
                 COleDateTime nowDate;
                 nowDate.ParseDateTime( str2 );
                 if(nowDate>=begin && nowDate<=end){
                    flag=true;
                 }else{
                    flag=false;
                 }
             }
            mysql_free_result(result);
            mysql_close(&m_sqlCon);
            getchar();
        }    
    }catch (...){  
         AfxMessageBox(_T("未知錯誤!"));
    }

    return flag;
}