关闭

c与mysql连接和一个简单查询的例子

1407人阅读 评论(0) 收藏 举报

今天给新来的同事做mysql培训,用到的一个例子:
连接数据库test 用户名root密码abc
在里面有一个username的表,describe username结果如下
mysql> describe username;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(10)     | YES  |     | NULL    |       |
| username | varchar(32) |      | PRI |         |       |
+----------+-------------+------+-----+---------+-------+

mysql> select * from username;
+------+----------+ 
| id   | username |
+------+----------+
|    1 | sfs      |
+------+----------+
1 row in set (0.00 sec)


[b:f09d522785]本文目的查找执行select id from username这个语句并打印结果[/b:f09d522785]
[code:1:f09d522785]
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>
MYSQL mysql;
main()
{
char host[32]="localhost";
char user[32]="root";
char passwd[32]="abc";
char dbname[32]="test";

if( mysql_init(&mysql) == NULL )
{
syslog(LOG_USER|LOG_INFO,"inital mysql handle error/n");
return 1;
}
if (mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)
{
syslog(LOG_USER|LOG_INFO, "Failed to connect to database: Error: %s/n",mysql_error(&mysql));
return 1;
}
else syslog(LOG_USER|LOG_INFO, "connect to database: /n");
find_ps();
db_close();
return 0;
}
int db_close()
{
       mysql_close(&mysql);
        return 0;
}


int  find_ps ()
{
MYSQL_ROW m_row;
MYSQL_RES *m_res;
char sql[1024],username[32];
int res=1;
int *id;
sprintf(sql,"select id from username");
if(mysql_query(&mysql,sql) != 0)
{
syslog(LOG_USER|LOG_INFO, "select ps_info Error: %s/n",mysql_error(&mysql));
return res;
}
m_res = mysql_store_result(&mysql);
if(m_res==NULL)
{
syslog(LOG_USER|LOG_INFO, "select username Error: %s/n",mysql_error(&mysql));
res = 3;
return res;
}
if(m_row = mysql_fetch_row(m_res))
{
printf("m_row=%d/n",atoi(m_row[0]));
res = 0;
}
mysql_free_result(m_res);
return res;
}
[/code:1:f09d522785]
编译命令
gcc -g connect_db.c -L/usr/lib/mysql -lmysqlclient -lz
注意:
如果/tmp/ccTGmMS21.o: In function `main':
/tmp/ccTGmMS21.o(.text+0x11): undefined reference to `mysql_init'
那么参数增加-L/usr/lib/mysql -lmysqlclient  
如果
usr/lib/mysql/libmysqlclient.a(my_compress.o): In function `my_uncompress':
my_compress.o(.text+0xaa): undefined reference to `uncompress'
那么增加-lz参数

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:458596次
    • 积分:5820
    • 等级:
    • 排名:第4368名
    • 原创:90篇
    • 转载:132篇
    • 译文:2篇
    • 评论:80条
    文章分类