c/c++ 使用c/c++连接到mysql

一、mysql c/c++库

1. 安装mysql c/c++库:
sudo apt install libmysqlclient-dev
2. 查看安装路径:
$ mysql_config --cflags --libs
-I/usr/include/mysql 
-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -ldl
# 在编译包含mysql.h的源文件时,需要添加编译选项:
gcc `mysql_config --cflags --libs` main.c -o main

二、使用mysql库

假设有一个d_school的database,里面包含了一个d_class的table,其表结构如下:

mysql>use d_school;
mysql>>show create table t_class;
+---------+-----------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                      |
+---------+-----------------------------------------------------+
| t_class | CREATE TABLE `t_class` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `class_id` int(11) NOT NULL,
  `teacher` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 |
+---------+----------------------------------------------------+

  1. 连接到mysql库:c/c++ 使用c/c++连接到mysql_第1张图片
  2. demo:
	Mysql_connection()
	{
		MYSQL mysql_conn;
		const char *host = "localhost";
		const char *user = "root";
		const char *passwd = "password";
		const char *db = "d_school";
		int  port = 0;
		const char *unix_socket = NULL;
		unsigned long clientflag = 0;	
		mysql_init(&sql_conn);
		if(NULL == mysql_real_connect(&mysql_conn, 
							host,
						  	user,
						   	passwd,
						   	db,
						   	port,
						   	unix_socket,
						   	clientflag)){			
			cerr << "connection default:\n";
			cerr << "\terrno:"   << mysql_errno(&mysql_conn);
			cerr << "\n\terror:" << mysql_error(&mysql_coon) << endl;
		}else{
			cout << "connection success." << endl;
		}
		mysql_close(&mysql_conn);
	}
  1. 运行结果:
$ ./main
connection success.

你可能感兴趣的:(C语言,linux,mysql)