每次在使用数据库的时候就去尝试连接数据,如果连接失败则关闭数据库,重新初始化:
void *joseph_db_connect(void *in)
{
//to connect the db
MYSQL_DB_JOSEPH *db = in;
int res = 0;
char value = 1;
db->conn_ptr = mysql_real_connect(db->conn_ptr, db->db_host,\
db->db_user, db->db_pass, db->db_name, 0, NULL, 0);
mysql_options(db->conn_ptr, MYSQL_OPT_RECONNECT, (char *)&value);
if (db->conn_ptr) {
// printf("Connection success %d\n",EXIT_SUCCESS);
} else {
printf("DB connection failed ERROR %s\n", mysql_error(db->conn_ptr));
}
return db;
}
int jrm_test_db_connect(void * in)
{
int mysql_connect_err = 0;
MYSQL_DB_JOSEPH *db = (MYSQL_DB_JOSEPH *)in;
mysql_connect_err = mysql_ping(db->conn_ptr);
eric_print("mysql_connect_err %d\n", mysql_connect_err);
if(mysql_connect_err !=0)
{
eric_print("mysq client connected is done\n");
jrm_db_close(db);
jrm_db_init();
return -1;
}
return 1;
}
void *get_jrm_db_ptr(void)
{
MYSQL_DB_JOSEPH *db = &joseph_db;
if ( jrm_test_db_connect(db) < 0)
{
eric_print("The db is colse connected\n");
db = &joseph_db;
}
else
eric_print("The db is connected ok\n");
return db;
}