1. 创建数据库
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代码访问数据库
// 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;
}
// 执行指定字符串的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=-lmysqlclient
all:mysqlcli.c
$(CC) mysqlcli.c -o mysqlcli $(ADDLIB)
clean:
-rm mysqlcli
4. 执行
$ ./mysqlcli
0001 10001
0002 10002
0003 10003
0004 10004