这是我不久前编写的一个程序的复制粘贴(或多或少),该程序使用他们的 C API 连接到 MySQL:
#include <stdio.h>
#include <stdlib.h>
#include <my_global.h>
#include <mysql.h>
typedef struct
{
char host[20];
char user[25];
char pass[50];
}DB_CONN_PARAMS;
MYSQL * connect_db(DB_CONN_PARAMS *params)
{
MYSQL *connection = mysql_init(NULL);//init connection
if (connection == NULL)
{//check init worked
fprintf(stderr, "%s\n", mysql_error(connection));
exit(EXIT_FAILURE):
}
//connect:
if (mysql_real_connect(
connection,
params->host,
params->user,
params->pass,
NULL,0,NULL,0)
==NULL)
{//connection failed?
fprintf(stderr, "%s\n", mysql_error(connection));
mysql_close(connection);
exit(EXIT_FAILURE):
}
return connection;
}
int main()
{
MYSQL *db;
DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
//just an alternative way of passing connection params, find a struct easier
params->host = "127.0.0.1";
params->user = "root";
params->pass = "mySuperSecretPass";
MYSQL * connect_db(DB_CONN_PARAMS *params);
db = connect_db(params);
//we don't need the struct anymore
free(params);
params = NULL;
//do stuff
mysql_close(db);//close connection, of course!
return EXIT_SUCCESS;
}
我的大部分灵感来自MySQL 网站上的代码示例。他们确实工作,诚实。
编译时,您必须牢记一些事情。上面的代码应该像这样使用 gcc 编译得很好:
gcc yourCode.c -std=c99 `mysql_config --cflags --libs` -o yourBin
当涉及到执行查询时,如您所愿,我建议您将 mysql.com 上的 C-API 文档添加为书签。
如果不使用准备好的语句,您的代码最终可能看起来像:
int main()
{
MYSQL *db;
char query_str[150];//query string here
int num1, num2, q_status;//your ints, + 1 to check success of query
DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
params->host = "127.0.0.1";
params->user = "root";
params->pass = "mySuperSecretPass";
MYSQL * connect_db(DB_CONN_PARAMS *params);
db = connect_db(params);
free(params);
//get numbers
scanf("%d %d", num1, num2);
//insert num1, num2 and sum into query string
sprintf(query_str,
"INSERT INTO your_db.table (num1, num2, sum) VALUES (%d,%d,%d);",
num1,num2,(num1 + num2)
);
//run our query
q_status = mysql_query(db, query_str);
if (q_status)
{//insert failed
fprintf(stderr, "Failed to execute \"%s\"\n%s\n", query_str, mysql_error(db));
mysql_close(db);
exit(EXIT_FAILURE);
}
//YaY, it worked!
printf("Insert successful:\nQuery used: \"%s\"\n", query_str);
mysql_close(db);
return EXIT_SUCCESS;
}
但这忽略了结果集、准备好的语句以及所有其他在实际程序中有用的东西。请浏览我在答案中链接到的文档,这并不难理解,有时只是有点小题大做,MySQL C API ...