PC SOFT

FORUMS PROFESSIONNELS
WINDEVWEBDEV et WINDEV Mobile

Accueil → WINDEV Mobile 2024 → Initialize Database Sqlite in Windev Mobile in Android
Initialize Database Sqlite in Windev Mobile in Android
Débuté par adrianoboller, 18 nov. 2014 13:58 - 4 réponses
Membre enregistré
3 661 messages
Popularité : +175 (223 votes)
Posté le 18 novembre 2014 - 13:58
ProcedureDB_InitializeDatabase()
//Connect

ok,TabelasOk isboolean=False
sDatabaseNameisstring="FaixaVermelha.db"
sDatabaseNameJournalisstring="FaixaVermelha.db-journal"

nCurrentDBVersionisint=1
nDBVersionInstalledisint
bFirstStartupisboolean

NextTitle("Atenção")

IFInSimulatorMode() =TrueTHEN
//Os arquivos de imagens de icones, splash e dados Sqlite e HF devem estar dentro da pasta EXE
IFfFileExist(CompleteDir(fDataDir())+"t000_configuracao.fic") =False
Info("Arquivos da base de dados do ipnone não localizados",CompleteDir(fDataDir())+"t000_configuracao.fic")
END
END

//LOCAL DA BASE DE DADOS
IFInSimulatorMode() =False
gsBasePath=gsAppDir+ ["/DB/"] +sDatabaseName
gsBasePathJournal=gsAppDir+ ["/DB/"] +sDatabaseNameJournal
IFNOTfDirectoryExist(gsAppDir+ ["/DB/"])THEN
DB_Diretorios()
END
ELSE
gsBasePath=gsAppDir+ ["\DB\"] +sDatabaseName
gsBasePathJournal=gsAppDir+ ["\DB\"] +sDatabaseNameJournal
IFNOTfDirectoryExist(gsAppDir+ ["\DB\"])THEN
DB_Diretorios()
END
END

// Database version
nDBVersionInstalled=LoadParameter(PREF_DB,0)
IFnDBVersionInstalled<>nCurrentDBVersionTHEN
DB_Update(nDBVersionInstalled,nCurrentDBVersion)
END

// Parameters of the connection
//Connn is Connection = Conn

Connn is Connection

Connn..Provider=hNativeAccessSQLite

Connn..Access=hOReadWrite

Connn..Source=gsBasePath

// Establish the connection
HChangeConnection("*",Connn)

// Establish the connection
// Quando nao tem import usa esse: HChangeConnection("*",Conn)
HChangeConnection(t000_configuracao,Connn)
HChangeConnection(t001_cliente,Connn)
HChangeConnection(t002_avisos,Connn)
HChangeConnection(t003_gps,Connn)
HChangeConnection(t004_cartoescreditos,Connn)
HChangeConnection(t005_favoritos,Connn)
HChangeConnection(t006_enderecos,Connn)
HChangeConnection(t007_tempodistancia,Connn)
HChangeConnection(t008_inicial,Connn)
HChangeConnection(t009_taxislogados,Connn)
HChangeConnection(t010_corridasagendadas,Connn)
HChangeConnection(t011_motivo_cancelamento,Connn)
HChangeConnection(t012_pesquisa_satisfacao,Connn)
HChangeConnection(t013_historico,Connn)
HChangeConnection(t014_finalidades,Connn)
HChangeConnection(t015_pontosturisticos,Connn)
HChangeConnection(t016_memo,Connn)

//Estrutura dos arquivos
DB_DeleteTodosArquivos("N")// Se for S zera a base de dados e fecha o programa, caso seja N não remove os dados da base, portanto atenção

//Valida a existencia dos arquivos
IFNOTfFileExist(gsBasePath)THEN

bFirstStartup=True

IFNOTfExtractResource(sDatabaseName,gsBasePath)ORNOTfFileExist(gsBasePath)ORNOTfFileExist(gsBasePathJournal)THEN

//Exclui e cria uma nova base de dados

fDelete(gsBasePath)
fDelete(gsBasePathJournal)

fCreate(gsBasePath)

HCreation(t000_configuracao,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t001_cliente,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t002_avisos,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t003_gps,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t004_cartoescreditos,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t005_favoritos,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t006_enderecos,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t007_tempodistancia,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t008_inicial,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t009_taxislogados,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t010_corridasagendadas,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t011_motivo_cancelamento,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t012_pesquisa_satisfacao,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t013_historico,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t014_finalidades,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t015_pontosturisticos,"",gsBasePath,gsBasePathJournal,hChangeCharset)
HCreation(t016_memo,"",gsBasePath,gsBasePathJournal,hChangeCharset)

//Info("Base criada com sucesso")

END

END

// Open the connection
IFHOpenConnection(Connn) =FalseTHEN
Error("Failure connecting to the SQLite Android database",HErrorInfo())
ELSE

TabelasOk=HCreationIfNotFound("*","",gsBasePath,gsBasePath,hChangeCharset+hDelayedOpening+hNoLink)

HCreationIfNotFound(t000_configuracao)
HCreationIfNotFound(t001_cliente)
HCreationIfNotFound(t002_avisos)
HCreationIfNotFound(t003_gps)
HCreationIfNotFound(t004_cartoescreditos)
HCreationIfNotFound(t005_favoritos)
HCreationIfNotFound(t006_enderecos)
HCreationIfNotFound(t007_tempodistancia)
HCreationIfNotFound(t008_inicial)
HCreationIfNotFound(t009_taxislogados)
HCreationIfNotFound(t010_corridasagendadas)
HCreationIfNotFound(t011_motivo_cancelamento)
HCreationIfNotFound(t012_pesquisa_satisfacao)
HCreationIfNotFound(t013_historico)
HCreationIfNotFound(t014_finalidades)
HCreationIfNotFound(t015_pontosturisticos)
HCreationIfNotFound(t016_memo)

HCreationIfNotFound("*")
END


IFTabelasOk=TrueTHEN

HDescribeConnection(Connn,"","","Sqlite","dbo",hNativeAccessSQLite,hOReadWrite,"")

ok=HChangeConnection("*",Connn)

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Alteracao de Estrutura das tabelas//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IFInSimulatorMode() =FalseTHEN
ok=UpdateDb_1(gsBasePath,"t005_favoritos","A005_Cidade","30")
ok=UpdateDb_1(gsBasePath,"t005_favoritos","A005_Uf","2")

ok=UpdateDb_1(gsBasePath,"t008_inicial","t008_cidade","30")
ok=UpdateDb_1(gsBasePath,"t008_inicial","t008_uf","2")

ok=UpdateDb_1(gsBasePath,"t010_corridasagendadas","t010cidade","30")
ok=UpdateDb_1(gsBasePath,"t010_corridasagendadas","t010uf","2")
ok=UpdateDb_1(gsBasePath,"t010_corridasagendadas","t010latitude","12")
ok=UpdateDb_1(gsBasePath,"t010_corridasagendadas","t010longitude","12")
END
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// In Android, the data files are in SQLite
IFInAndroidMode()THEN
// Describes the connection that will be used
IFHDescribeConnection(Connn,"","","","",hAccessSQLiteAndroid,hOReadWrite) =FalseTHEN
Error("Não foi possivel criar ou acessar a base de dados.",HErrorInfo(hErrMessage))
EndProgram(True)
END

// Changes the connection of the application files
IFHChangeConnection("*",Connn) =FalseTHEN
Error("Não foi possivel criar ou acessar a base de dados",HErrorInfo(hErrMessage))
EndProgram(True)
END

//Agilidade na gravação dos dados
IFInAndroidSimulatorMode() =FalseTHEN
sErro isstring=AtivarDesativarIntegridadeSQLite("desativar")
IFsErro<>"ok"THEN
Error(sErro)
EndProgram()
END
ELSE
//HExecuteSQLQuery(Query,Minhaconexao,hQueryWithoutCorrection,"PRAGMA synchronous = OFF;")
//HExecuteSQLQuery(Query,Minhaconexao,hQueryWithoutCorrection,"PRAGMA journal_mode = OFF;")
END


END


ELSE

Info("Não foi possivel criar ou acessar a base de dados.")

EndProgram(True)

END

RESULT(TabelasOk)
>
Membre enregistré
3 661 messages
Popularité : +175 (223 votes)
Posté le 18 novembre 2014 - 13:58
//Ativar Desativar Integridade SQLite

import android.database.sqlite.*;
import android.content.Context;
import android.util.*;
import android.database.*;
PUBLIC static stringAtivarDesativarIntegridadeSQLite(stringsTipo){
stringDB_NAME="FaixaVermelha.db";
stringalterQuery="";
SQLiteDatabase db;
try{
db=getContexteApplication().openOrCreateDatabase(DB_NAME,0,null);
try{
IF(sTipo.toLowerCase() =="desativar"){
db.execSQL("PRAGMA synchronous = OFF;");
db.rawQuery("PRAGMA journal_mode = OFF;",null);
}
ELSE{
db.execSQL("PRAGMA synchronous = FULL;");
db.rawQuery("PRAGMA journal_mode = DELETE;",null);
}
db.close();
RETURN"ok";
}catch(SQLException e) {
db.close();
RETURNe.getMessage();
}
}catch(SQLException e) {
RETURNe.getMessage();
}
}

//Utilizando a função no seu aplicativo
//=====================================
//IF InAndroidSimulatorMode() = False THEN
//sErro is string = AtivarDesativarIntegridadeSQLite("desativar")
//IF sErro <> "ok" THEN
//Error(sErro)
//EndProgram()
//END
//ELSE
//HExecuteSQLQuery(Query,Minhaconexao,hQueryWithoutCorrection,"PRAGMA synchronous = OFF;")
//HExecuteSQLQuery(Query,Minhaconexao,hQueryWithoutCorrection,"PRAGMA journal_mode = OFF;")
//END
>
Membre enregistré
3 661 messages
Popularité : +175 (223 votes)
Posté le 18 novembre 2014 - 13:59
ProcedureDB_Update(nDBVersionInstalled_ isint,nCurrentDBVersion isint)

IFnDBVersionInstalled_>0THEN
// Perform the update here
// At this time, the database is still in version 1 therefore there is no code
ELSE
SaveParameter("DB",nCurrentDBVersion)
END
>
Membre enregistré
3 661 messages
Popularité : +175 (223 votes)
Posté le 18 novembre 2014 - 13:59
//Variaiveis
CONSTANT
PREF_DB="DB"
END
>
Membre enregistré
3 661 messages
Popularité : +175 (223 votes)
Posté le 18 novembre 2014 - 14:01
In iOS + HyperfileSql
*************************

CONSTANT
HF_FILE_LIST= [
t000_configuracao.fic
t001_cliente.fic
t002_avisos.fic
t003_Gps.fic
t004_cartoescreditos.fic
t005_favoritos.fic
t006_enderecos.fic
t007_tempodistancia.fic
t008_inicial.fic
t009_taxislogados.fic
t010_corridasagendadas.fic
t011_motivo_cancelamento.fic
t012_pesquisa_satisfacao.fic
t013_historico.fic
t014_finalidades.fic
t015_pontosturisticos.fic
t016_memo.fic
t000_configuracao.ndx
t001_cliente.ndx
t002_avisos.ndx
t003_Gps.ndx
t004_cartoescreditos.ndx
t005_favoritos.ndx
t006_enderecos.ndx
t007_tempodistancia.ndx
t008_inicial.ndx
t009_taxislogados.ndx
t010_corridasagendadas.ndx
t011_motivo_cancelamento.ndx
t012_pesquisa_satisfacao.ndx
t013_historico.ndx
t014_finalidades.ndx
t015_pontosturisticos.ndx
t016_memo.ndx
t000_configuracao.mmo
t001_cliente.mmo
t002_avisos.mmo
t003_Gps.mmo
t004_cartoescreditos.mmo
t005_favoritos.mmo
t006_enderecos.mmo
t007_tempodistancia.mmo
t008_inicial.mmo
t009_taxislogados.mmo
t010_corridasagendadas.mmo
t011_motivo_cancelamento.mmo
t012_pesquisa_satisfacao.mmo
t013_historico.mmo
t014_finalidades.mmo
t015_pontosturisticos.mmo
t016_memo.mmo
]
END



// HF_FILE_LIST // constante global atualizar ao criar nova tabela

// Variable
sHFFile isstring

// Extracts the HF files
FOR EACHSTRINGsFile OF HF_FILE_LIST SEPAREEbyCR
sHFFile=CompleteDir(fDataDir()) +sFile

IFfFileExist(sHFFile) =FalseTHEN
fExtractResource(sFile,sHFFile)
END

END

//Cria se não existir a tabela
WHEN EXCEPTION IN
HCreationIfNotFound(*)
DO
Error("SQL error: "+HError())
TabelasOk=False
ELSE
TabelasOk=True
END
>