MYSQL C API : mysql_real_connect()

MYSQL * mysql_real_connect(

MYSQL *mysql,
const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag);

// 连接到MYSQL 数据库服务器 在头文件mysql.h 中声明
// 参数的说明请参考百度百科

代码范例:

 1 #include <iostream>
 2 #include <mysql.h>
 3 #include <string>
 4 
 5 #include <assert.h>
 6 
 7 int main()
 8 {
 9     MYSQL *ms_conn = mysql_init(NULL);
10     if (ms_conn == NULL)
11     {
12         std::cout << "Error: mysql_init failed." << std::endl;
13         return 0;
14     }
15     std::cout << "Info: mysql_init successful." << std::endl;
16 
17     MYSQL *ms_res = NULL;
18     ms_res = mysql_real_connect(ms_conn, "localhost", "root", "123456", 
19             "db_name", 0, NULL, 0);
20     if (ms_res == NULL)
21     {
22         std::cout << "Error: connect mysql failed: " << mysql_error(ms_conn) << std::endl;
23         mysql_close(ms_conn), ms_conn = NULL;
24         return 0;
25     }
26     std::cout << "Info: mysql connect successful." << std::endl;
27 
28     // ... // 其他操作
29     
30     // 使用完释放系统资源
31     mysql_close(ms_conn), ms_conn = NULL;
32 }

 

posted on 2015-09-07 11:54  独孤酷酷  阅读(2537)  评论(0编辑  收藏  举报