c语言连接数据库mysql
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
下面是C语言连接mysql数据库简单例子:
编译方式:
gcc -I /usr/local/mysql/include/ -L /usr/local/mysql/lib/ -l mysqlclient select.c -o select
源码:
#include
#include
#include
#include "/usr/local/mysql/include/mysql.h"
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "192.168.1.99";
char *user = "test";
char *password = "test_passwd";
char *database = "count";
double tvalue1 = 0.93;
char st[123];
time_t s;
s = time((time_t*)NULL );
sprintf(st, "%d", s);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
char sql[1024]="SELECT * FROM money_change WHERE c_datetime <= ";
strcat(sql,st);
strcat(sql,"-3000 AND c_datetime > ");
strcat(sql,st);
strcat(sql,"-5000 AND c_type = 0 UNION ALL SELECT * FROM money_change WHERE
c_datetime <= ");
strcat(sql,st);
strcat(sql," AND c_datetime > ");
strcat(sql,st);
strcat(sql,"-3600 ORDER BY c_type");
printf("%s\n",sql);
if (mysql_query(conn, sql)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL){
printf("c_goldnote\t=\t%9s\n",row[5]);
}
mysql_free_result(res);
mysql_close(conn);
}