//
// Created by gxf on 2020/2/4.
//
#include
#include
#include
void query(MYSQL *conptr);
void updateSql(MYSQL *mysql, char *updateSQL);
int main() {
MYSQL *conptr = NULL;
conptr = mysql_init(NULL);
if (!conptr) {
printf("init mysql fail\n");
exit(1);
}
conptr = mysql_real_connect(conptr, "localhost", "root", "", "test",
3306, NULL, 0);
if (!conptr) {
printf("connect mysql fail\n");
exit(1);
}
printf("connect mysql success\n");
// query
query(conptr);
// insert
updateSql(conptr, "insert into person(name, address) values('guanxianseng', 'chengdu')");
// delete
updateSql(conptr, "delete from person where name='guanxianseng'");
// update
updateSql(conptr, "update person set address='chengdu1111' where name='guanxiangfei'");
// query
query(conptr);
mysql_close(conptr);
return 0;
}
// query
void query(MYSQL *conptr) {
MYSQL_RES *resptr;
MYSQL_ROW row;
MYSQL_FIELD filed;
int res, i, j;
res = mysql_query(conptr, "select name, address from person");
// query fail
if (res) {
printf("query db fail: %s\n", mysql_error(conptr));
return;
}
resptr = mysql_store_result(conptr);
if (!resptr) {
printf("store fail:%s\n", mysql_error(conptr));
return;
}
printf("row nums: %d\n", mysql_num_rows(resptr));
j = mysql_num_fields(resptr);
while ((row = mysql_fetch_row(resptr))) {
for (i = 0; i < j; i++) {
printf("%s \t", row[i]);
}
printf("\n");
if (mysql_errno(conptr)) {
printf("retrive faile: %s\n", mysql_error(conptr));
return;
}
} //while
// mysql_free_result(conptr);
}
// insert update delete
void updateSql(MYSQL *mysql, char *updateSQL) {
int res;
res = mysql_query(mysql, updateSQL);
if (res) {
// update fail
printf("insert errorno: %d error: %s\n", mysql_errno(mysql), mysql_error(mysql));
} else {
// update success
printf("update rows nums:%d\n", mysql_affected_rows(mysql));
}
}
cmaklist.txt
# mysql demo
include_directories(/usr/local/include/mysql)
link_directories(/usr/local/mysql/lib)
link_libraries(mysqlclient)
add_executable(mysql-demo2 mysql-demo1.c)
create table sql
create table person(name varchar(50), address varchar(100));