QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1114|回复: 2

关于c语言和MYSQL接口中的问题?

[复制链接]
发表于 2005-11-22 11:44:16 | 显示全部楼层 |阅读模式
我现在在用C语言和MYSQL来编写代码,但是遇到下列问题:
         mysql_query(mysql, "select src,dst,channel,billsec,answer,end,amaflags,disposition from cdr where amaflags=3 and disposition=???");

在问号(???)这里我想写变量名,而不是常量,但不知道怎么进行字符串拼接,试过很多次都不行,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
int main()
{
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
unsigned int num_fields,num_rows;
int i,num = 1;
char* dis;
dis = malloc(100);
dis = "ANSWERED";
mysql = malloc(sizeof(MYSQL));
if ( !(mysql = mysql_connect(NULL, "localhost","root",NULL))){
fprintf(stderr, "Failed to connect to database: Errors: %s\n", mysql_error(mysql));
return -1;
}

if (mysql_select_db(mysql, "cdr") )
{
printf("select db wrong: %s \n", mysql_error(mysql));
return -1;
}

mysql_query(mysql, "select src,dst,channel,billsec,answer,end,amaflags,disposition from cdr where amaflags=3 and disposition=$dis);   

result = mysql_store_result(mysql);
if (result == NULL)
{
printf("Error: %s\n", mysql_error(mysql));
return -1;
}

num_fields = mysql_num_fields(result);
num_rows = mysql_num_rows(result);
while((row = mysql_fetch_row(result)))
{
        printf("%d\n",num);

for( i = 0; i < num_fields; i++ ){
        printf("%s\n",row);
}
        num++;
printf("\n");
}

mysql_free_result(result);
mysql_close(mysql);

return 0;
}

发表于 2005-11-22 11:47:55 | 显示全部楼层
char *buf;
//给buf分配内存
sprintf(buf,"select src,dst,channel,billsec,answer,end,amaflags,disposition from cdr where amaflags=3 and disposition=%s",dis);
mysql_query(mysql,buf);
//释放buf
回复

使用道具 举报

 楼主| 发表于 2005-11-22 12:07:14 | 显示全部楼层
太感谢了, 成功了,
不过sprintf(buf,"select src,dst,channel,billsec,answer,end,amaflags,disposition from cdr where amaflags=3 and disposition=%s",dis);

改成sprintf(buf,"select src,dst,channel,billsec,answer,end,amaflags,disposition from cdr where amaflags=3 and disposition='%s'",dis);

太感谢了,谢谢斑竹!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-11-3 02:27 , Processed in 0.038395 second(s), 15 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表