Is it possible to connect a C-based application to a database?

Asked

Viewed 2,146 times

2

We usually use files to save data using language C (at least). It is possible to connect a relational database to any application made in C? If yes, do you need a library for this and how is this connection made? Preferably Mysql.

  • 1

    Yeah, that’s all you wanna know?

  • I’d like to know how to make the connection.

  • In which database?

  • Any relational database, preferably mysql

  • 1

    Take a look at this article.

2 answers

7


Why wouldn’t there be a way?

Programming languages are just mechanisms for communicating with the computer. What communication does with databases is usually organized code in libraries. Each database provides its way to do this. Many databases are written in C so it is quite direct. In other languages we usually have some adaptation layer.

Example in Mysql:

#include <my_global.h>
#include <mysql.h>

int main() {
    MYSQL *con = mysql_init(NULL);
    if (con == NULL) {
        fprintf(stderr, "%s\n", mysql_error(con));
        exit(1);
    }
    if (mysql_real_connect(con, "localhost", "root", "root_pswd", NULL, 0, NULL, 0) == NULL) {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }
    if (mysql_query(con, "CREATE DATABASE testdb")) {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }
    mysql_close(con);
}

I put in the Github for future reference.

Documentation.

Download.

2

If there is like, Postgresql even uses many functions in C and has a library for it. Just add #include

You will need to find out where the libpq-fe file is. h, then, when compiling the program, we pass the directory above within the gcc -I option: gcc -the program -I/usr/include/pgsql program. c -lpq

This is assuming your library is in /usr/include/pgsql. Switch to the directory where yours is. You may need to use the -L option and the directory instead of the -I option.

More details on: source long live linux

Browser other questions tagged

You are not signed in. Login or sign up in order to post.