C program mysql connection

2020-07-22 19:28发布

I'm working on a simple c program that has to connect to my database, then do a query and then close the connection.

int main()
{
    MYSQL *conn;
    conn = mysql_init(NULL);

    if (conn == NULL) {
        printf("Error %u %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

    if (mysql_real_connect(conn, "localhost", "root", "root", NULL, 8889, NULL, 0)) {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

    if (mysql_query(conn, "create database testdb")) {
        printf("Error %u: %s",mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

    mysql_close(conn);
    return 0;
}

This code compiles but when I run it, it will exit after the mysql_query() statement.

The following error is returned:

Error 2006: MySQL server has gone away

I used google to search for an answer and ended up here:

http://dev.mysql.com/doc/refman/5.0/en/gone-away.html

标签: mysql c
3条回答
做个烂人
2楼-- · 2020-07-22 19:56

Your connection's failing - your test should be:

if (mysql_real_connect(...) == NULL) {
  printf("...");
  exit(1);
}

mysql_real_connect returns NULL on failure, or the connection handle on success.

--Dave

查看更多
一夜七次
3楼-- · 2020-07-22 20:11

/* Simple C program that connects to MySQL Database server*/

 #include <mysql.h>
 #include <stdio.h>
 main() {
     MYSQL *conn;
     MYSQL_RES *res;
     MYSQL_ROW row;
     char *server = "localhost";
     char *user = "root";
     char *password = "PASSWORD"; /* set me first */
     char *database = "mysql";
     conn = mysql_init(NULL);
     /* Connect to database */
     if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }

    /* send SQL query */
    if (mysql_query(conn, "show tables")) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }
    res = mysql_use_result(conn);

    /* output table name */
    printf("MySQL Tables in mysql database:\n");
    while ((row = mysql_fetch_row(res)) != NULL)
        printf("%s \n", row[0]);

    /* close connection */
    mysql_free_result(res);
    mysql_close(conn);
}
查看更多
够拽才男人
4楼-- · 2020-07-22 20:17

Return Values

A MYSQL* connection handle if the connection was successful, NULL if the connection was unsuccessful. For a successful connection, the return value is the same as the value of the first parameter.

http://dev.mysql.com/doc/refman/5.0/en/mysql-real-connect.html

your connection is not being made

查看更多
登录 后发表回答