c 连接mysql

apt-get install libmysqlclient-dev

mysql 使用的是xampp 需要指定sock

源码:main.c

#if defined(_WIN32) || defined(_WIN64)  //为了支持windows平台上的编译
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>  //我的机器上该文件在/usr/local/include/mysql下
 
//定义数据库操作的宏,也可以不定义留着后面直接写进代码
#define SELECT_QUERY "select username from test where userid = %d"
 
int main(int argc, char **argv) //char **argv 相当于 char *argv[]
{
    MYSQL mysql,*sock;    //定义数据库连接的句柄,它被用于几乎所有的MySQL函数
    MYSQL_RES *res;       //查询结果集,结构类型
    MYSQL_FIELD *fd ;     //包含字段信息的结构
    MYSQL_ROW row ;       //存放一行查询结果的字符串数组
    char  qbuf[160];      //存放查询sql语句字符串
    
    if (argc != 2) {  //检查输入参数
        fprintf(stderr,"usage : mysql_select <userid>\n\n");
        exit(1);
    }
    
    mysql_init(&mysql);
    if (!(sock = mysql_real_connect(&mysql,"localhost","root","","test",3306, "/opt/lampp/var/mysql/mysql.sock" ,0))) {
        fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql));
        perror("");
        exit(1);
    }
    
    sprintf(qbuf,SELECT_QUERY,atoi(argv[1]));
    if(mysql_query(sock,qbuf)) {
        fprintf(stderr,"Query failed (%s)\n",mysql_error(sock));
        exit(1);
    }
    
    if (!(res=mysql_store_result(sock))) {
        fprintf(stderr,"Couldn't get result from %s\n", mysql_error(sock));
        exit(1);
    }
    
    printf("number of fields returned: %d\n",mysql_num_fields(res));
        
    while (row = mysql_fetch_row(res)) {
        printf("Ther userid #%d 's username is: %s\n", atoi(argv[1]),(((row[0]==NULL)&&(!strlen(row[0]))) ? "NULL" : row[0])) ; 
        puts( "query ok !\n" ) ; 
    } 
    
    mysql_free_result(res);
    mysql_close(sock);
    exit(0);
    return 0;   //. 为了兼容大部分的编译器加入此行
}

编译:

 gcc -o mysql_select ./main.c -lmysqlclient

 


 

简单类封装

 test.sql   

mysql>use test;

mysql>source ~/test.sql;
DROP TABLE IF EXISTS `test`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `test`
--

LOCK TABLES `test` WRITE;
/*!40000 ALTER TABLE `test` DISABLE KEYS */;
INSERT INTO `test` VALUES (1,'hxl'),(2,'sqlite'),(3,'test'),(4,'for'),(5,'linux');
/*!40000 ALTER TABLE `test` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2012-07-02 23:52:14

 

main.cc

#include    <cstdlib>
#include    <fstream>
#include    <iomanip>   
#include    <iostream> 
extern "C"
{ 
#include        <mysql/mysql.h>
#include        <string.h>

}
using namespace std;

class MyDb
{
    private:
        MYSQL mysql,*sock;    //定义数据库连接的句柄,它被用于几乎所有的MySQL函数
        MYSQL_RES *res;       //查询结果集,结构类型
        MYSQL_FIELD *fd ;     //包含字段信息的结构
        MYSQL_ROW row ;       //存放一行查询结果的字符串数组

    public:
        MyDb()
        {
            cout<<"nothing"<<endl;
        }
        MyDb(char *ip, char *user, char *passwd, char *db_name, int port, char *socket)
        {
            mysql_init(&mysql);
            if (!(sock = mysql_real_connect(&mysql, ip, user, passwd, db_name, port, socket ,0))) {
                fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql));
                perror("");
                exit(1);
            }

        }
        ~MyDb()
        {
            mysql_free_result(res);
            mysql_close(sock);  
            cout<<"connect destoryed"<<endl;
        }
        void  get(char *str)
        {
            if(mysql_query(sock,str)) {
                fprintf(stderr,"Query failed (%s)\n",mysql_error(sock));
                exit(1);
            }

            if (!(res=mysql_store_result(sock))) {
                fprintf(stderr,"Couldn't get result from %s\n", mysql_error(sock));
                exit(1);
            }
            printf("number of fields returned: %d\n",mysql_num_fields(res));

            while (row = mysql_fetch_row(res)) {
                printf("Ther username is: %s\n",(((row[0]==NULL)&&(!strlen(row[0]))) ? "NULL" : row[0])) ; 
                puts( "query ok !" ) ; 
            } 

        }
};

    int
main ( int argc, char *argv[] )
{
    MyDb test("localhost","root","","test", 3306,"/opt/lampp/var/mysql/mysql.sock");
    test.get("select value from test where id = 1");
    return EXIT_SUCCESS;
}        // ----------  end of function main  ---------- 

 

 

编译:

g++ -g -o mysql_select ./mysql.cc -lmysqlclient

 

posted @ 2012-07-01 12:51  wangkangluo1  阅读(669)  评论(0编辑  收藏  举报