mysql的C执行语句样例

发表于:2007-07-04来源:作者:点击数: 标签:
其使用C语言来访问 数据库 很方便~ typedef struct st_mysql NET .net ; /* Communication parameters */ gptr connector_fd; /* ConnectorFd for SSL */ char *host,*user,*passwd,* unix _socket, *server_version,*host_info,*info,*db; unsigned int por

其使用C语言来访问数据库很方便~

typedef struct st_mysql {
  NET          .net;            /* Communication parameters */
  gptr          connector_fd;   /* ConnectorFd for SSL */
  char          *host,*user,*passwd,*unix_socket,
                *server_version,*host_info,*info,*db;
  unsigned int  port,client_flag,server_capabilities;
  unsigned int  protocol_version;
  unsigned int  field_count;
  unsigned int  server_status;
  unsigned long thread_id;      /* Id for connection in server */
  my_ulonglong affected_rows;
  my_ulonglong insert_id;       /* id if insert on table with NEXTNR */
  my_ulonglong extra_info;              /* Used by mysqlshow */
  unsigned long packet_length;
  enum mysql_status status;
  MYSQL_FIELD   *fields;
  MEM_ROOT      field_alloc;
  my_bool       free_me;        /* If free in mysql_close */
  my_bool       reconnect;      /* set to 1 if automatic reconnect */
  struct st_mysql_options options;
  char          scramble_buff[9];
  struct charset_info_st *charset;
  unsigned int  server_language;
} MYSQL;

#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>

int
main(int argc, char **argv) {

   MYSQL mysql;
   MYSQL_RES *res;
   MYSQL_ROW row;

   unsigned int num_fields;
   unsigned int i;
   char *query="SELECT * FROM JOB";

   /*Initializing MySQL connection*/
   if(mysql_init(&mysql)==NULL) {
      printf("Failed to initate MySQL connection\n");
      exit(1);
   }

   /*Connecting to MySQL server*/
   if (!mysql_real_connect(&mysql,"127.0.0.1","username","password",NULL,0
   ,NULL,0)) {
      printf( "Failed connect to the server: %s\n",
       mysql_error(&mysql));
      exit(1);
   }

   /*Selecting database*/
   if(mysql_select_db(&mysql,"CONTRACTING")!=0)
      printf( "Failed select CONTRACTING: %s\n", mysql_error(&mysql));

   /*Performing SQL query*/
   if(mysql_query(&mysql,query)) {
      printf("MySQL query error: %s\n",mysql_error(&mysql));
      mysql_close(&mysql);
      exit(1);
   }
   res = mysql_store_result(&mysql);

   if (res) {
      num_fields = mysql_num_fields(res);
      while ((row = mysql_fetch_row(res)))
      {
         for(i = 0; i < num_fields; i++) {
            printf("%s\t",  row[i] ? row[i] : "NULL");
         }
         printf("\n");
      }
      mysql_free_result(res);
   }
   else {
      if(mysql_field_count(&mysql) > 0)
      {
         printf( "Error getting records: %s\n", mysql_error(&mysql));
      }
      else {
         printf( "Failed to find any records and caused an error:
         %s\n", mysql_error(&mysql));
      }
   }
   mysql_close(&mysql);
}

原文转自:http://www.ltesting.net