我如何将c程序连接到mysql?

时间:2013-11-05 06:30:18

标签: mysql c

这是我的c程序,它连接到名为(add_tbl)的数据库。现在我的查询是我应该提到的数据库名称。没有它,它将如何连接到数据库并存储结果?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <my_global.h>
#include <mysql.h>

typedef struct
{
    char host[20];
    char user[25];
    char pass[50];
}DB_CONN_PARAMS;

int main()
{
    MYSQL *db;
    char query_str[150];
    int num1, num2, q_status;
    DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
    params->host = "127.0.0.1";
    params->user = "root";
    params->pass = "Password";
    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
    printf(query_str,"INSERT INTO add_tbl (num1, num2, sum) VALUES (%d,%d %d);",
           num1,num2,(num1 + num2));

    //run the 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);
    }

    printf("Insert successful:\nQuery used: \"%s\"\n", query_str);
    mysql_close(db);
    return EXIT_SUCCESS;
}

我的数据库表名是'add_tbl' 在哪里指定数据库名称。我无法理解它。请有人指导我。

1 个答案:

答案 0 :(得分:1)

我不知道您的connect_db()做了什么,但您应该使用mysql_real_connect()。在那里,您可以将数据库设置为参数db

如果您以后想要更改默认数据库,可以使用mysql_select_db()

是的,而不是做

DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
params->host = "127.0.0.1";
params->user = "root";
params->pass = "Password";
MYSQL * connect_db(DB_CONN_PARAMS *params);
db = connect_db(params);
free(params);

您可能希望将其(为简单起见)更改为

DB_CONN_PARAMS params = {};
params.host = "127.0.0.1";
params.user = "root";
params.pass = "Password";
// MYSQL * connect_db(DB_CONN_PARAMS *params); // omit that here, it belongs either to the header or above the current function
db = connect_db(&params);

甚至

DB_CONN_PARAMS params = { .host = "127.0.0.1", .user = "root", .pass = "Password" };
db = connect_db(&params);