安装mysql 获得 mysql.h 建立C接口

安装mysql 获得 mysql.h 建立C接口 今天费了好长时间终于让C操作MYSQL成功了,在此把方法记下来,留着以后用。hoho~

先安装mysql 代码: sudo apt-get install mysql-server mysql-client

再装开发包 代码: sudo apt-get install libmysqlclient15-dev

安装完以后,C代码里添加头文件 代码: #include

编译方法: 代码: gcc $(mysql_config --cflags) xxx.c -o xxx $(mysql_config --libs)

可以用以下代码测试一下 代码:

 

代码
   
     
#include < stdlib.h >
#include
< stdio.h >

#include
" mysql.h "

int main( int argc, char * argv[]) {
MYSQL
* conn_ptr;

conn_ptr
= mysql_init(NULL);
if ( ! conn_ptr) {
fprintf(stderr,
" mysql_init failed\n " );
return EXIT_FAILURE;
}

conn_ptr
= mysql_real_connect(conn_ptr, " localhost " , " root " , " 2009 " ,
" mydata " , 0 , NULL, 0 );

if (conn_ptr) {
printf(
" Connection success\n " );
}
else {
printf(
" Connection failed\n " );
}

mysql_close(conn_ptr);

return EXIT_SUCCESS;
}

C++ 的代码!

代码
   
     
C ++ 语言代码在Linux下操作MySQL数据库
文章关键字:
| Linux | C ++| 语言 | 代码 | 操作 | MySQL | 数据库 |

代码:

#include

#include

#include
" /usr/local/include/mysql/mysql.h " // 安装的mysql的头文件所在的位置

using namespace std;

string host = " 数据库地址 " ;

string user = " 用户名 " ;

string pwd = " 密码 " ;

string dbname = " 数据库 " ;

string sql = " 查询语句 " ;

unsigned
int port = 3309 ;#端口号

int status;

int main(){

  MYSQL
* mysql;

  mysql
= mysql_init( 0 );

  MYSQL_RES
* result;

  MYSQL_ROW row;

  
if (mysql_real_connect(mysql,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),port,NULL,CLIENT_FOUND_ROWS) == NULL){

    cout
<< " connect failure! " << endl;

    
return EXIT_FAILURE;

  }
else {

    cout
<< " connect success! " << endl;

  }

  mysql_set_character_set(mysql,
" gbk " );

  status
= mysql_query(mysql,sql.c_str());

  
if (status != 0 ){

    cout
<< " query failure! " << endl;

  }

  cout
<< " the status is : " << status << endl;

  result
= mysql_store_result(mysql);

  
while (row = mysql_fetch_row(result)){

    cout
<< row[ 1 ] << " | " << row[ 2 ] << endl;

  }

  mysql_free_result(result);

  mysql_close(mysql);

}

编译:

g
++ - o test test.cpp - lmysqlclient - I / usr / local / include / mysql / - L / usr / local / lib / mysql

后面的那些用来指定mysql安装的时候包含路径和库文件路径,具体与你机器上的mysql安装的路径有关。

 

 原文链接地址:http://forum.ubuntu.org.cn/viewtopic.php?f=44&p=1031013

 

你可能感兴趣的:(mysql)