Linux C language database, linuxc language database
MySQL is an open-source free database widely used in Linux, and is the first choice for storing data in Linux applications.
To install MySQL in Ubuntu, run the following command at a terminal prompt:
$ Sudo apt-get install mysql-server mysql-client
Once the installation is complete, the MySQL server should be automatically started. After the default MySQL is installed, the user is root. During the installation process, you will be prompted to enter password, which is the password you need to log on to the database later.
MySQL can be accessed in different languages, including C, C ++, JAVA, Perl, Python, and PHP. Before accessing the MySQL database in C language, install the MySQL development database:
$ Sudo apt-get install libmysqlclient15-dev
After the installation is complete, the header file: mysql. h required for operating MySQL in C language is included in/uer/include/mysql;
Connecting from C to a MySQL database involves two steps:
1. initialize a MySQL structure.
2. Connect
The following is a simple example.
File Name connect. c
#include <stdlib.h>#include <stdio.h>#include <mysql/mysql.h>MYSQL *conn_ptr;int main(){conn_ptr = mysql_init(NULL);if(!conn_ptr){fprintf(stderr, "mysql_init failed!\n");return -1;}conn_ptr = mysql_real_connect(conn_ptr,"localhost","root","acm","testdb",0,NULL,0);if(conn_ptr)printf("Connection succeed!\n");else{printf("Connection failed\n");return -2;}mysql_close(conn_ptr);printf("Connection closed.\n");return 0;}
Because mysql files are used, you must specify them during compilation. The command for terminal compilation is as follows:
Gcc-I/usr/include/mysql connect1.c-L/usr/lib/mysql-lmysqlclient-o connect1
The program execution result is as follows:
Connection succeed!
Connection closed.
It can be seen that connecting to a database is very simple.