天天看點

一個簡單通路Mysql資料庫的例程

#include <winsock.h>

#include <mysql.h>

#include <iostream>

using namespace std;

#ifndef NULL

#define NULL 0

#endif

int main(int argc, char* argv[])

{

 MYSQL mysql;

 mysql_init(&mysql);

 MYSQL* pMysql = mysql_real_connect(&mysql //! mysql [3月/16日/2010年 馬強]

                                                             ,_T("127.0.0.1") //! 資料庫所在位址 [3月/16日/2010年 馬強]

                                                             ,_T("root") //! 使用者名 [3月/16日/2010年 馬強]

                                                             ,_T("") //! 密碼 [3月/16日/2010年 馬強]

                                                             ,_T("") //! 使用的資料庫名 [3月/16日/2010年 馬強]

                                                             ,MYSQL_PORT //! 連接配接端口 [3月/16日/2010年 馬強]

                                                             ,NULL

                                                             ,0);

 if (NULL != pMysql)

 {

        char szSql[] = _T("select * from shool");

        //! 執行查詢 [3月/16日/2010年 馬強]

        if (0 == mysql_query(&mysql,szSql))

        {

               MYSQL_FIELD* pmysql_field = NULL;

               MYSQL_RES*   pmysql_res   = NULL;

               MYSQL_ROW    mysql_row    = NULL;

               pmysql_res = mysql_store_result(&mysql);

               int n = 0;

              //! 列出所有列标 [3月/16日/2010年 馬強]

              unsigned int nNum = mysql_num_fields(pmysql_res);

              printf(_T("--------------------------------------------/n| "));

              for (int i = 0; i < nNum; ++i)

              {

                   pmysql_field = mysql_fetch_field(pmysql_res);

                   printf(_T("%s | "),pmysql_field->name);

              }

              printf(_T("/n--------------------------------------------/n"));

             //! 資料 [3月/16日/2010年 馬強]

            while (mysql_row = mysql_fetch_row(pmysql_res))

            {

                for (int i = 0; i < nNum; ++i)

               {

                   printf(_T("| %s     "),mysql_row[i]);

               }

               printf(_T("/n"));

            }

            cout<<_T("/n--------------------------------------------/n");

            //! 釋放查詢占用記憶體 [3月/16日/2010年 馬強]

            mysql_free_result(pmysql_res);

      }

   }

   mysql_close(&mysql);

   return 0;

}