Linux C Connection MySQL

Source: Internet
Author: User
Tags mysql create mysql create database

First make sure that GCC and MySQL are installed on the system.

If it is not installed first. For CentOS

Yum-y Install GCC

Yum-y Install Mysql-server

You must also install Mysql-devel

Installation Success Detection:

[Email protected] mysql]# Rpm-qa | grep ' gcc '  libgcc-4.4.7-4.el6.x86_64gcc-4.4.7-4.el6.x86_64[[email protected] mysql]# rpm-qa | grep ' MySQL ' Mysql-5.1.73-3.el6_5.x86_64mysql-devel-5.1.73-3.el6_5.x86_64mysql-libs-5.1.73-3.el6_5.x86_ 64mysql-server-5.1.73-3.el6_5.x86_64

Then start MySQL

Service mysqld Start

Go to MySQL CREATE DATABASE and table

Mysql> CREATE DATABASE c_test;mysql> use c_testcreate TABLE ' user ' (' id '  int (one) ' Not NULL auto_increment, ' name '  varchar (+) CHARACTER SET UTF8 COLLATE utf8_general_ci NULL DEFAULT ', PRIMARY KEY (' id ')) Engine=innodbdefault CHARACTER Set=utf8 collate=utf8_general_ci;mysql> insert into user (name) values (' Zhang San '), (' John Doe '), (' Harry ');mysql> select * from user;+----+--------+| ID | Name   |+----+--------+|  1 | Zhang San | |  2 | John Doe | |  3 | Harry |+----+--------+3 rows in Set (0.00 sec)

Create MYSQL.C

/* ============================================================================ name:connect.c Author: Linze return Version:Copyright:Your Copyright Notice Description:connect Mysql =========================================== ================================= * * #include <stdio.h> #include <stdlib.h> #include <string.h># Include <mysql/mysql.h>mysql *g_conn; MySQL connection mysql_res *g_res; MySQL record set Mysql_row g_row; String array, MySQL record line # define MAX_BUF_SIZE 1024//Buffer maximum byte number const char *g_host_name = "localhost"; const char *g_user_name = "ro OT "; const char *g_password =" 123456 "; const char *g_db_name =" c_test "; const unsigned int g_db_port = 3306;void print_mysq    L_error (const char *msg) {//prints the last error if (msg) printf ("%s:%s\n", MSG, Mysql_error (g_conn)); Else puts (mysql_error (G_conn));} int ExecuteSQL (const char * sql) {/*query The database according the sql*/if (mysql_real_query, SQL, G_conn (SQL))) If the failure return-1; Represents the failure of return 0;    Successful execution of}int Init_mysql () {//Initialize the connection//init the database connection G_conn = Mysql_init (NULL); /* Set character encoding, may be garbled */
mysql_query (G_conn, "set Nemas utf-8"); /* Connect the database * * if (!mysql_real_connect (G_conn, G_host_name, G_user_name, G_password, G_db_name, G_db_port, N ULL, 0))//if failure return-1; Whether the connection is already available//if (ExecuteSQL ("Set Names UTF8"))//if failed//return-1; return 0; Return success}int main (void) {if (Init_mysql ()); Print_mysql_error (NULL); Char Sql[max_buf_size]; if (ExecuteSQL (SQL)) Print_mysql_error (NULL); if (ExecuteSQL ("SELECT * from User"))//At the end of the sentence there is no semicolon print_mysql_error (NULL); G_res = Mysql_store_result (g_conn); Transfer result set from server to local, Mysql_use_result directly using recordset int inum_rows = Mysql_num_rows (g_res) on the server; The number of rows to be recorded int inum_fields = Mysql_num_fields (g_res); Get the number of columns of records printf ("Total%d records,%d fields per record \ n", Inum_rows, Inum_fields); Puts ("id\tname\n"); while ((G_row=mysql_fetch_row (g_res)))//print result set printf ("%s\t%s\n", G_row[0], g_row[1]); First, the second field mysql_free_result (G_res); Release result set Mysql_close (G_conn); Close link RETurn exit_success;}

Compile

Gcc-g-O mysql-i/usr/include/mysql/connect.c-l/usr/lib64/mysql/-lmysqlclient-lz

When compiling, be aware of the path of 2 paths, mysql.h and libmysqlclient.so.

Find mysql.h Path

[[email protected] mysql]# Find/-name ' mysql.h '  /usr/include/mysql/mysql.h

[[email protected] mysql]# Find/-name ' *mysqlclient* '/usr/lib64/mysql/libmysqlclient_r.so.16.0.0/usr/lib64/mysql/ libmysqlclient.so.16/usr/lib64/mysql/libmysqlclient_r.so.16/usr/lib64/mysql/libmysqlclient_r.so/usr/lib64/ mysql/libmysqlclient.so/usr/lib64/mysql/libmysqlclient.so.16.0.0

Run:

Operation Result:

A total of 3 records, 2 field ID per record      name1       Zhang 32       li 43       Harry

Be sure to keep the data table encoding, c file encoding consistency, otherwise garbled

Linux C Connection MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.