C语言链接数据库
一、解释一下函数功能和用法
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。
二、上示例代码
#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, "***.***.***.***", "usre_name", "password", "DataBase_name", port, 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 age where name='"; char select_query[] = "select * from age"; 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 age 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; }
三、结果截图
四、注意点
由于MySQL所用的头文件不是C语音标准库,所以一定要加上外部库,不然编译不过。
找不到库的,要先安装libmysqlclient-dev(整套流程教程传送门:https://www.cnblogs.com/zhuyp1015/p/3561470.html)