How To Connect C ++ to MySqL database

Source: Internet
Author: User

When using programming languages for program development, database operations are often performed. In C ++ programming language, how should this operation be performed? Here we will introduce in detail the specific operation methods for connecting C ++ to the MySqL database.

Sample Code for connecting C ++ to the MySqL database:

 
 
  1. #include < stdio.h>   
  2. #include < stdlib.h>   
  3. #include < string.h>   
  4. #include < mysql/mysql.h>   
  5. int main()  
  6. {   
  7. MYSQL *mysql;   
  8. MYSQL_RES *res;   
  9. MYSQL_ROW row;   
  10. char query[1024];   
  11. int t,r;   
  12. mysql=mysql_init(NULL);   
  13. if(!mysql_real_connect(mysql,"test","root","123","test",0,NULL,0))   
  14. {   
  15. printf( "Error connecting to database: %s\n",mysql_error(mysql));   
  16. }   
  17. else  
  18. printf("Connected\n");   
  19. sprintf(query,"select * from first");   
  20. t=mysql_query(mysql,query);   
  21. if(t)   
  22. {   
  23. printf("Error making query:%s\n",mysql_error(mysql));   
  24. }   
  25. else  
  26. printf("Query made\n");   
  27. res=mysql_use_result(mysql);   
  28. for(r=0;r< mysql_field_count(mysql);r++)  
  29. {   
  30. row=mysql_fetch_row(res);   
  31. if(row< 0)   
  32. break;   
  33. for(t=0;t< mysql_num_fields(res);t++)   
  34. printf("%s",row[t]);   
  35. printf("\n");   
  36. }   
  37. mysql_close(mysql);   
  38. return 0;   

This section describes how to connect C ++ to the MySqL database.

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.