请选择 进入手机版 | 继续访问电脑版
查看: 403|回复: 0

[运维管理] mysql_client

688

主题

688

帖子

2083

积分

猿er

Rank: 1

积分
2083
发表于 2016-8-14 17:49:15
<无详细内容>
  1. /* clang++ sql.cpp -o sql -lmysqlclient */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <mysql/mysql.h>
  6. #include <iostream>
  7. using namespace std;
  8. int main()
  9. {
  10. const char user[] = "root"; /* username */
  11. const char pswd[] = ""; /* password */
  12. const char host[] = "localhost"; /* or"127.0.0.1" */
  13. const char table[] = "test"; /* database */
  14. unsigned int port = 3306; /* server port */
  15. MYSQL myCont;
  16. MYSQL_RES *result;
  17. MYSQL_ROW sql_row;
  18. MYSQL_FIELD *fd;
  19. char column[32][32];
  20. int res;
  21. mysql_init( &myCont );
  22. if ( mysql_real_connect( &myCont, host, user, pswd, table, port, NULL, 0 ) )
  23. {
  24. cout << "connect succeed!" << endl;
  25. mysql_query( &myCont, "SET NAMES GBK" ); /* 设置编码格式,否则在cmd下无法显示中文 */
  26. res = mysql_query( &myCont, "select * from user" ); /* 查询 */
  27. if ( !res )
  28. {
  29. result = mysql_store_result( &myCont ); /* 保存查询到的数据到result */
  30. if ( result )
  31. {
  32. int i, j;
  33. cout << "number of result: " << (unsigned long) mysql_num_rows( result ) << endl;
  34. for ( i = 0; fd = mysql_fetch_field( result ); i++ ) /* 获取列名 */
  35. {
  36. strcpy( column[i], fd->name );
  37. }
  38. j = mysql_num_fields( result );
  39. for ( i = 0; i < j; i++ )
  40. {
  41. printf( "%s ", column[i]
  42. );
  43. }
  44. printf( "\n" );
  45. while ( sql_row = mysql_fetch_row( result ) ) /* 获取具体的数据 */
  46. {
  47. for ( i = 0; i < j; i++ )
  48. {
  49. printf( "%s\n", sql_row[i] );
  50. }
  51. printf( "\n" );
  52. }
  53. }
  54. }else {
  55. cout << "query sql failed!" << endl;
  56. }
  57. }else {
  58. cout << "connect failed!" << endl;
  59. }
  60. if ( result != NULL )
  61. mysql_free_result( result ); /* 释放结果资源 */
  62. mysql_close( &myCont ); /* 断开连接 */
  63. return(0);
  64. }
复制代码


回复

使用道具 举报