Chinaunix首页 | 论坛 | 博客
  • 博客访问: 31479
  • 博文数量: 12
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-08 20:21
文章分类

全部博文(12)

文章存档

2011年(1)

2009年(2)

2008年(9)

我的朋友
最近访客

分类: C/C++

2008-09-19 15:42:27

 
 

#include
#include
#include "mysql.h"
/*
* mysql_sample.c
*
* MySQL client program sample code
*
* by Robert on 2006.02.09
* Anta Systems, Inc.
*
* Compile options:
*   gcc -I/usr/include/mysql -L/usr/lib/mysql -o mysql_sample mysql_sample.c -lmysqlclient -lz
*
*/

/* global definition */
#define CONN_HOST "192.168.100.112"
#define CONN_USER "test"
#define CONN_PASS ""
#define CONN_DB   "test"

/* global MySQL handler */

MYSQL mysql;
void exiterr(int exitcode)
{
    fprintf( stderr, "%s\n", mysql_error(&mysql) );
    exit(exitcode);
}

int mysql_test()

{
    MYSQL_RES *res;
    MYSQL_ROW row;
    uint i = 0;
      /* 1. init MySQL handler */
   if (!mysql_init(&mysql))
    {
        exiterr(-1);
    }

      /* 2. connect to MySQL */
   if (!mysql_real_connect(&mysql, CONN_HOST , CONN_USER , CONN_PASS, NULL , MYSQL_PORT, NULL, 0))
    {
        exiterr(-2);
    }

    
/* 3. select Database */

    if (mysql_select_db(&mysql, CONN_DB))
    {
        exiterr(-3);
    }

      /* 4. excute a query */
   char *sqlstr = "SELECT * FROM test_table";
    if (mysql_query(&mysql, sqlstr))
    {
        exiterr(-4);
    }

      /* 5. store result */
   if (!(res = mysql_store_result(&mysql)))
    {
        exiterr(-5);
    }

    /* 6. fetch row and get the result */
    while((row = mysql_fetch_row(res)))
    {
        for (i=0 ; i < mysql_num_fields(res); i++)
        {
            printf("%s, ",row[i]);
        }
        printf("\n");
    }

      /* 7. free result */
   mysql_free_result(res);

      /* 8. close MySQL Connection */
   mysql_close(&mysql);
}

int main()
{
    mysql_test();
    return 0;

阅读(1064) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~