以下是我爲某個函數編寫的代碼,該函數應該始終在其自己的線程上運行,檢查數據庫以獲取新信息並將新信息附加到全局向量。我似乎遇到的問題是,經過各地這麼多次,都獲得成功,我會自發地得到這個錯誤:線程在檢查數據庫時拋出錯誤
Unhandled exception at 0x5B46F1F9 (libmysql.dll) in Project2.exe: 0xC0000005: Access violation reading location 0x000003B0.
也不太清楚怎麼了,但它似乎發生了if(connect){}
聲明之後因爲正確,因爲它崩潰,我看到Connection Failed!
打印聲明。我只是沒有理由爲什麼會失敗。我有一個類似的問題,是由於達到數據庫的最大連接數而引起的,但我不知道這將如何發生,因爲在if
聲明的每次迭代後,我都使用mysql_close(connect)
聲明。
void getNewFromDB(){
while(globalExit == false){
MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
/* This If is irrelevant and you don't need to show it. I kept it in for Fault Testing.*/
if(!connect) /* If instance didn't initialize say so and exit with fault.*/
{
fprintf(stderr,"MySQL Initialization Failed");
}
/* Now we will actually connect to the specific database.*/
connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);
/* Following if statements are unneeded too, but it's worth it to show on your
first app, so that if your database is empty or the query didn't return anything it
will at least let you know that the connection to the mysql server was established. */
if(connect){
printf("Connection Succeeded\n");
}
else{
printf("Connection Failed!\n");
}
MYSQL_RES *result; /* Create a pointer to recieve the return value.*/
MYSQL_ROW row; /* Assign variable for rows. */
mysql_query(connect,"SELECT * FROM locationTime ORDER BY id DESC");
/* Send a query to the database. */
result = mysql_store_result(connect); /* Receive the result and store it in res_set */
unsigned int numrows = mysql_num_rows(result); /* Create the count to print all rows */
row = mysql_fetch_row(result);
if(row[0] > ids.back()){
ids.push_back(row[0]);
dateTime.push_back(row[1]);
locs.push_back(setLocation(row[2]));
imgPaths.push_back(row[3]);
}
mysql_close(connect);
}
/* Close and shutdown */
}
編輯:所有給出的答案解決這個問題的一部分,我感謝你。但是現在我不明白的是,爲什麼在16000個請求之後突然間連接失敗?
這很可能是一個'null'指針AV。也許你的一個MySQL調用中的一個參數不允許爲'null'?最有可能的嫌疑是'mysql_query(connect,...)'連接'' – JensG
'mysql_real_connect'是否成功或失敗,你仍然跋涉。所有的代碼都應該移到'if(connect)'塊中。 –