A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C program to get records from the MySQL database table in Linux
Q:

C program to get records from the MySQL database table in Linux

0

C program to get records from the MySQL database table in Linux

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will connect to the MyDb database and then retrieve records from the "Employee" table using the "SELECT" command.

Program/Source Code:

The source code to retrieve records from MySql database table in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to retrieve records from MySql database 
//table in Linux.

#include <mysql.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char server[16] = "localhost";
    char username[16] = "root";
    char password[16] = "root";
    char database[16] = "MyDb";

    MYSQL* conn = mysql_init(NULL);
    MYSQL_ROW record;

    if (conn == NULL) {
        printf("MySQL initialization failed");
        return 1;
    }

    if (mysql_real_connect(conn, server, username, password, database, 0, NULL, 0) == NULL) {
        printf("Unable to connect with MySQL server\n");
        mysql_close(conn);
        return 1;
    }

    if (mysql_query(conn, "SELECT * FROM Employee")) {
        printf("Unable to connect with MySQL server\n");
        mysql_close(conn);
        return 1;
    }

    MYSQL_RES* rs = mysql_store_result(conn);

    if (rs == NULL) {
        printf("Unable to compile SQL statement\n");
        mysql_close(conn);
        return 1;
    }

    while (record = mysql_fetch_row(rs)) {
        printf("%s %s %s\n", record[0], record[1], record[2]);
    }
    mysql_close(conn);

    return 0;
}

Output:

$ gcc select.c -o select  `mysql_config --cflags --libs`
$ sudo ./select 
[sudo] password for arvind: 
101 KIRAN 10000
102 SUMAN 12000
103 RAMAN 16000

In the above program, we included the mysql.h header file to use MySql connectivity related functions. Here, we created variables serverusernamepassword, and database that are initialized values specific to the MySQL connectivity.

Here, we connected to the MyDb database in MySql server using mysql_real_connect() function and then retrieve records from "employee" table using mysql_query()mysql_store_result(), and mysql_fetch_row() functions and printed the all employee records on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now