Linux下MySQL C API简单示例
生活随笔
收集整理的這篇文章主要介紹了
Linux下MySQL C API简单示例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
1. 創(chuàng)建數(shù)據(jù)庫
drop?database?testdb;
commit;create?database?testdb;
commit;use?testdb;
commit;create?table?users(username?varchar(20)?not?null,password?varchar(20)?not?null
);
commit;insert?into?users(username,?password)?values('0001',?'10001');
insert?into?users(username,?password)?values('0002',?'10002');
insert?into?users(username,?password)?values('0003',?'10003');
insert?into?users(username,?password)?values('0004',?'10004');
commit; 2. C代碼訪問數(shù)據(jù)庫
//?mysqlcli.c #include?<stdio.h> #include?<stdlib.h> #include?<mysql/mysql.h>int?main(int?argc,?char?*argv[]) {int?i;char?sqlstr[]?=?"select?*?from?users";char?host[]?=?"127.0.0.1";char?user[]?=?"root";char?passwd[]?=?"lowkey2046";char?db[]?=?"testdb";unsigned?int?port?=?3306;char?*unix_socket?=?NULL;unsigned?long?clientflag?=?0;MYSQL?mysql;MYSQL_RES?*result;MYSQL_ROW?row;//?獲得或初始化一個MYSQL結構?if?(mysql_init(&mysql)?==?NULL)?{printf("mysql_init?error:?%s\n",?mysql_error(&mysql));goto?done1;}//?連接一個MySQL服務器?if?(mysql_real_connect(&mysql,?host,?user,?passwd,?db,?port,?unix_socket,?clientflag)?==?NULL){printf("mysql_real_connect?error:?%s\n",?mysql_error(&mysql));goto?done1;}//?執(zhí)行指定字符串的SQL查詢?if?(mysql_query(&mysql,?sqlstr)?!=?0)?{printf("mysql_query?error:?%s",?mysql_error(&mysql));goto?done2;}//?生成結果集if?((result?=?mysql_store_result(&mysql))==?NULL)?{printf("mysql_free_result?error:?%s\n",?mysql_error(&mysql));goto?done2;}//?從結果集合中取得下一行while?((row?=?mysql_fetch_row(result))?!=?NULL)?{//?遍歷一行結果for?(i?=?0;?i?<?mysql_num_fields(result);?i++)?{printf("%10s",?row[i]?!=?NULL???row[i]?:?"NULL");}printf("\n");}//?釋放結果集mysql_free_result(result); done2://?關閉一個服務器連接mysql_close(&mysql);done1:return?0; }3. Makefile
CC=gcc ADDLIB=-lmysqlclientall:mysqlcli.c$(CC)?mysqlcli.c?-o?mysqlcli?$(ADDLIB)clean:-rm?mysqlcli4. 執(zhí)行
$?./mysqlcli?0001?????100010002?????100020003?????100030004?????10004轉(zhuǎn)載于:https://my.oschina.net/lowkey2046/blog/551704
總結
以上是生活随笔為你收集整理的Linux下MySQL C API简单示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: samba linux文件服务器 ch
- 下一篇: java(十六) 对象的this引用