Hello everyone, I am trying to use the unreal api to make a connection to a local database with the SQLite plugins. Where I am stuck is in a part of my code, where I create an instance of the FSQLiteDatabase class as shown in the video that I will leave at the end. When I call a function where the database is opened, I first check if that instance is valid, but even though I declare it and initialize it using new FSQLiteDatabase(), this variable is still invalid. My code:
bool UUnrealDatabase::CreateConnectionToDatabase(FString Path)
{
Database=new FSQLiteDatabase();
if (!Database->IsValid()||!Database->Open(*Path, ESQLiteDatabaseOpenMode::ReadWrite))
{
UE_LOG(LogTemp, Warning, TEXT("Failed to open database: %s"), *(!Database->IsValid()?"Not Valid":Database->GetLastError()));
return false;
}
return true;
}
void UUnrealDatabase::CloseDatabase() const
{
if(Database->IsValid())
{
if (!Database->Close())
{
UE_LOG(LogTemp, Warning, TEXT("Failed to close database: %s"), *Database->GetLastError());
}
else
{
delete Database;
}
}
}
bool UUnrealDatabase::AddDatabaseRow(FString TableName, TMap<FString, FString> Parameters)
{
if(!Database->IsValid()) return false;
FSQLitePreparedStatement Statement;
FString AllKeys="";
TArray<FString> Keys;
Parameters.GenerateKeyArray(Keys);
GenerateQueryParameters(AllKeys,Keys);
FString AllValues="";
TArray<FString> Values;
Parameters.GenerateValueArray(Values);
GenerateQueryParameters(AllValues,Values);
FString query="INSERT INTO "+TableName+" "+AllKeys+" VALUES"+AllValues;
Statement.Create(*Database, *query, ESQLitePreparedStatementFlags::None);
if(!Statement.IsValid() || BindStatement(&Statement, Keys, Values)) return false;
return Statement.Execute();
}
bool UUnrealDatabase::ConnectToLocalDatabase(const FString Path)
{
return CreateConnectionToDatabase(Path);
}
void UUnrealDatabase::GenerateQueryParameters(FString& QueryParam, const TArray<FString> Params)
{
QueryParam="(";
for (int i=0; i<Params.Num(); i++)
{
QueryParam=QueryParam+Params[i];
if(i<Params.Num()-1)
QueryParam=QueryParam+", ";
}
QueryParam=QueryParam+")";
}
bool UUnrealDatabase::BindStatement(FSQLitePreparedStatement* Statement, const TArray<FString> Keys, const TArray<FString> Values)
{
for(int i=0; i<Keys.Num(); i++)
{
if(!Statement->SetBindingValueByName(*Keys[i], *Values[i]))
return false;
}
return true;
}
UUnrealDatabase::UUnrealDatabase()
{
Database = new FSQLiteDatabase();
}
First I create the UUnrealDatabase class, and in the constructor I initialize this variable, then from the blueprints, even leaving a small margin of time, after a second of delay, I call the function to establish connection with the SQLite database.
I’m pretty new to c++, I can get by in c++, but I don’t understand why when I instantiate this class, it’s invalid. What could be doing wrong?
Source: Unreal Engine C++ Tutorial | How To Save Data With SQLite Database