1.在linux上安装好Mysql;查看本博客安装教程
2. 编译:gcc -I/usr/include/mysql XXXX.c -L/usr/lib/mysql -lmysqlclient -o XXXX
(详解:需要在gcc编译时指定 头文件地址,用命令mysql_config,即可获取mysql安装后头文件所在位置,库文件所在位置,之后指定相关路径。-I /usr/include/mysql,同时需要指定mysql的库文件, 搜索目录为:-L /usr/lib64/mysql ,之后指定需要的库文件名:-lmysqlclient)
一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mysql.h"
int main() {
MYSQL conn;
int res;
MYSQL_RES * result;
MYSQL_ROW row;
mysql_init(&conn);
if (mysql_real_connect(&conn, "localhost", "root", "0701", "wuchen", 3369, NULL, 0)) {
printf("coneect mysql successful\n请选择功能:\n");
int choose;
char str1[20], str2[20];
char insert_query[80];
char delete_query[50] = "delete from test where name='";
char select_query[] = "select * from test";
printf("1.insert\n2.select\n3.delete\n");
while (scanf("%d", &choose)) {
switch (choose) {
case 1:
printf("姓名 年龄:\n");
memset(insert_query, 0, sizeof(insert_query));
//insert
scanf("%s %s", str1, str2);
strcat(insert_query, "insert into test values('");
strcat(insert_query, str1);
strcat(insert_query, "',");
strcat(insert_query, str2);
strcat(insert_query, ")");
printf("SQL语句: %s\n", insert_query);
res = mysql_query(&conn, insert_query);
if (!res) {
printf("insert %lu rows\n", (unsigned long)mysql_affected_rows(&conn));
}
else {
printf("insert error\n");
}
break;
case 2:
//select
printf("SQL语句: %s\n", select_query);
if (mysql_query(&conn, select_query) != 0) {
fprintf(stderr, "查询失败!\n");
exit(1);
}
else {
if ((result = mysql_store_result(&conn)) == NULL) {
fprintf(stderr, "保存结果集失败!\n");
exit(1);
}
else {
while ((row = mysql_fetch_row(result)) != NULL) {
printf("name is %s , ", row[0]);
printf("age is %s\n", row[1]);
}
}
}
break;
case 3:
printf("姓名:\n");
scanf("%s", str1);
strcat(delete_query, str1);
strcat(delete_query, "'");
//delete
printf("SQL语句: %s\n", delete_query);
res = mysql_real_query(&conn, delete_query, (unsigned int)strlen(delete_query));
if (!res) {
printf("delete successful\n");
}
else {
printf("delete error\n");
}
break;
}
}
mysql_close(&conn);
}
return 0;
}
一、解释一下函数功能和用法
1.mysql_real_connect
函数原型:MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long client_flag)
参数说明:
host:本地用localhost或127.0.0.1,远程写IP;
user、passwd:登陆数据库的用户名密码
db:数据库名
port:数据库所用的端口(MySQL一般为3306)
unix_socket:先写个NULL(官方解释:如果unix_socket不是NULL,该字符串描述了应使用的套接字或命名管道)
client_flag:先写个0(指定特定功能)
2.mysql_real_query
函数原型:int mysql_real_query(MYSQL *mysql, const char *query, unsigned int length)
参数说明:
query:SQL语句;
length:SQL语句长度
3.mysql_store_result
函数原型:MYSQL_RES *mysql_store_result(MYSQL *mysql)
返回值说明:具有多个结果的MYSQL_RES结果集合。如果出现错误,返回NULL。
4.mysql_fetch_row
函数原型:MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
参数说明:具有多个结果的MYSQL_RES结果集合
返回值说明:在mysql_store_result()之后使用时,如果没有更多的行可检索时,mysql_fetch_row()返回NULL。