siara-cc / esp32_arduino_sqlite3_lib

Sqlite3 Arduino library for ESP32
Apache License 2.0
365 stars 66 forks source link

error 14 (SQLITE_CANTOPEN) when open database after do several "SELECT" command #95

Open asbs-eng opened 1 month ago

asbs-eng commented 1 month ago

i use esp32 (arduino) after several select command (read_data())

int read_data() { sqlite3 *db1; int rc = sqlite3_open("/sd/test.db", &db1);

if (rc) {
Serial.print("Can't open database ("); Serial.print(String(rc)); Serial.print(") : "); Serial.println(sqlite3_errmsg(db1)); } else {
sqlite3_stmt stmt; String sql = "SELECT FROM tbl_data WHERE tgl>'2024-07-31 08:08:21' AND counter>450 ORDER BY tgl DESC , counter DESC;";

int rcrc = sqlite3_prepare_v2(db1,sql.c_str(),-1,&stmt,NULL); 
if (rcrc != SQLITE_OK) {
  Serial.println("Error Fetch Data");
}

const char * dt_id;
const char * dt_tgl;
int    dt_cnt;

if (sqlite3_step(stmt) != SQLITE_ROW) {      
  sqlite3_close(db1);   
  sqlite3_finalize(stmt);      

} else {

  while (sqlite3_step(stmt) == SQLITE_ROW) {    
    dt_id   = (const char *) sqlite3_column_text(stmt,0);
    dt_tgl  = (const char *) sqlite3_column_text(stmt,1);
    dt_cnt  = sqlite3_column_int(stmt,2);
    Serial.print(dt_id);
    Serial.print("  ");
    Serial.print(dt_tgl);
    Serial.print("  ");
    Serial.print(dt_cnt);
    Serial.println("  ");
  }
  sqlite3_close(db1);   
  sqlite3_finalize(stmt);
}

}
return rc; }

i have error 14 (SQLITE_CANTOPEN) unable to open database file int rc = sqlite3_open("/sd/test.db", &db1); where i get rc = 14

siara-cc commented 1 month ago

@asbs-eng

  1. I think sqlite3_close() should be executed after sqlite3_finalize()
  2. Why open the database everytime for running SQL? It can be kept open while executing prepared statements on it?
asbs-eng commented 1 month ago

yes you right i add sqlite3_reset() before sqlite3_finalize() and now it run perfectly , i think it because memory issue so after do select statement i clear memory.
i open database everytime for running SQL because there are more than 1 database each for different user and the code above is just a concise example for the entire program. In this way, I think the problem has been resolved, thank you