TotalCross Forums
September 10, 2010, 06:50:36 am *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: TotalCross - the heaven of mobile application development
 
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: The table format is incompatible with Litebase version. Please update your table  (Read 856 times)
twelon
Newbie
*
Posts: 8


View Profile
« on: February 05, 2010, 01:47:21 pm »

Boa tarde,

Estou com este erro quando faço um getRowCount e nao consigo entender porque.....
Será que me podem ajudar?

Obrigado

Code:
if (bean.getDriver().getRowCount("auditory") != 0)

A tabela esta foi criada do seguinte modo:

Code:
public void initTables() {
int size;

String[] table = new String[9];
table[0] = "CREATE TABLE auditory(audit_id int,n_shop char(20),shop char(50),start_date char(8),end_date char(8))";

size = table.length;
for (int i = 0; i < size; i++) {
try {
getDriver().execute(table[i]);
} catch (Exception e) {
}
}
}

E a ligaçao:
Code:
public LitebaseConnection driver = null;

public LitebaseConnection getDriver() {
if (driver == null) {
driver = LitebaseConnection.getInstance(appCrid, null);
}
return driver;
}

O erro:
Code:
>>>>>>> CAUGHT UNHANDLED EXCEPTION IN EVENT THREAD:
     [java] litebase.DriverException: The table format is incompatible with Litebase version. Please update your tables. (737)
     [java] at litebase.e.b(Unknown Source)
     [java] at litebase.e.a(Unknown Source)
     [java] at litebase.LitebaseConnection.a(Unknown Source)
     [java] at litebase.LitebaseConnection.getRowCount(Unknown Source)
Logged
JulianaImperial
Full Member
***
Posts: 231



View Profile WWW
« Reply #1 on: February 05, 2010, 02:24:44 pm »

Tem como postar o código de sua aplicação por completo?
Logged
twelon
Newbie
*
Posts: 8


View Profile
« Reply #2 on: February 05, 2010, 02:37:56 pm »

Boa tarde,

No proximo codigo estão as tabelas usadas na aplicação.

Code:
public void initTables() {
int size;

String[] table = new String[9];
table[0] = "CREATE TABLE auditory(audit_id int,n_shop char(20),shop char(50),start_date char(8),end_date char(8))";
table[1] = "CREATE TABLE config(pda_id int,password char(9),ip char(32),lang char(2))";
table[2] = "CREATE TABLE report(audit_id int,question_id int,question char(70),question_type int)";
table[3] = "CREATE TABLE turn_report(turn_id int,question_id int,question_answer int)";
table[4] = "CREATE TABLE sales(turn_id int,sale_date char(9),buyers int,sale_value double,pay_type int,pay_method int,sinal double,tax double)";
table[5] = "CREATE TABLE turn_entries(turn_id int,turn_hour int,entries int)";
table[6] = "CREATE TABLE turn(turn_id int,audit_id int,begin_date char(14),end_date char(14),state char(1),turn int,auditor char(20),close_value double)";
table[7] = "CREATE TABLE tax(tax double,def char(1))";
table[8] = "CREATE TABLE cur(cur char(3),def char(1))";

size = table.length;
for (int i = 0; i < size; i++) {
try {
getDriver().execute(table[i]);
} catch (Exception e) {
}
}
}

No codigo seguinte respresente a unica classe que mexe na tabela em que nos da o erro. (auditory)

Code:
package windows;

import litebase.PreparedStatement;
import models.ButtonUser;
import models.LabelUser;
import totalcross.sys.Convert;
import totalcross.ui.ComboBox;
import totalcross.ui.Container;
import totalcross.ui.Edit;
import totalcross.ui.Window;
import totalcross.ui.dialog.MessageBox;
import totalcross.ui.event.ControlEvent;
import totalcross.ui.event.Event;
import totalcross.ui.gfx.Color;
import beans.AppBean;

/**
 * @author hrmartins
 */
public class Tax extends Window {

String audit = null;
LabelUser[] auditInfo = null;
AppBean bean = null;
ButtonUser[] button = null;
ComboBox cbLocals = null;
ComboBox cbLocalTax = null;
ComboBox cbLocalCurr = null;
boolean refresh = false;
StringBuffer sb = null;
Edit shopEdit = null;
String[][] taxs = null;

public Tax(AppBean bean, String audit) {
super(bean.getString("TITLE_11"), RECT_BORDER);
this.bean = bean;
this.audit = audit;
sb = bean.sb;
setBackForeColors(Color.BRIGHT, bean.GREEN);
setRect(CENTER, CENTER, 220, 234);
}

public void changeLocalTax(int localId) {
cbLocalTax.removeAll();
for (int i = 0; i < taxs[localId].length; i++) {
if (taxs[localId][i] == null) {
break;
}
cbLocalTax.add(taxs[localId][i] + " %");
}
cbLocalTax.setSelectedIndex(cbLocalTax.size() - 1);
}

public boolean createAuditory() {
boolean retVal = false;

int audit_id;
String n_shop = null;
String shop = null;
String begin_date = null;
String end_date = null;
int n_questions;
String[] st = null;

MessageBox mb = new MessageBox(bean.getString("BOX_TITLE_3"), bean.getString("MESSAGE_22"));
mb.popupNonBlocking();

PreparedStatement stmt = null;
try {
int pos = 0;
st = Convert.tokenizeString(audit, '|');

audit_id = Convert.toInt(st[pos++]);
n_shop = st[pos++];
shop = st[pos++];
begin_date = st[pos++];
end_date = st[pos++];
n_questions = Convert.toInt(st[pos++]);

bean.getDriver().executeUpdate("delete from auditory");
bean.getDriver().executeUpdate("delete from report");
bean.getDriver().executeUpdate("delete from tax");
bean.getDriver().executeUpdate("delete from cur");

stmt = bean.getDriver().prepareStatement("INSERT INTO auditory VALUES (?,?,?,?,?)");
stmt.setInt(0, audit_id);
stmt.setString(1, n_shop);
stmt.setString(2, shop);
stmt.setString(3, begin_date);
stmt.setString(4, end_date);
stmt.executeUpdate();

stmt = bean.getDriver().prepareStatement("INSERT INTO report VALUES (?,?,?,?)");
try {
for (int i = 0; i < n_questions; i++) {
stmt.setInt(0, audit_id);
stmt.setInt(1, Convert.toInt(st[pos++]));
stmt.setString(2, st[pos++]);
stmt.setInt(3, Convert.toInt(st[pos++]));
stmt.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
bean.getDriver().executeUpdate("delete from auditory");
bean.getDriver().executeUpdate("delete from report");
}

try {
stmt = bean.getDriver().prepareStatement("INSERT INTO TAX VALUES(?,?)");
for (int i = 0; i < 10; i++) {
if (taxs[cbLocals.getSelectedIndex()][i] == null) {
break;
}
stmt.setDouble(0, Convert.toDouble(taxs[cbLocals.getSelectedIndex()][i]));
stmt.setString(1, i == cbLocalTax.getSelectedIndex() ? "X" : "");
stmt.executeUpdate();
}

stmt = bean.getDriver().prepareStatement("INSERT INTO CUR VALUES(?,?)");
int size = cbLocalCurr.size();
for (int i = 0; i < size; i++) {
stmt.setString(0, cbLocalCurr.getItemAt(i).toString());
stmt.setString(1, i == cbLocalCurr.getSelectedIndex() ? "X" : "");
stmt.executeUpdate();
}

} catch (Exception e) {
e.printStackTrace();
bean.getDriver().executeUpdate("delete from auditory");
bean.getDriver().executeUpdate("delete from report");
bean.getDriver().executeUpdate("delete from tax");
bean.getDriver().executeUpdate("delete from cur");
}

retVal = true;
} catch (Exception e) {
e.printStackTrace();
retVal = false;
} finally {
mb.unpop();
stmt = null;
st = null;
n_shop = null;
shop = null;
begin_date = null;
end_date = null;
}

return retVal;
}

public void initAuditInfoLabels() {
auditInfo = new LabelUser[3];
String[] st = Convert.tokenizeString(audit, '|');
auditInfo[0] = new LabelUser(st[0], font, Color.BRIGHT, Color.BLACK);
auditInfo[1] = new LabelUser(st[1], font, Color.BRIGHT, Color.BLACK);

shopEdit = new Edit();
shopEdit.setText(st[2]);
shopEdit.setKeyboard(Edit.KBD_NONE);
shopEdit.setEditable(false);

sb.setLength(0);
sb.append(bean.parseDate(st[3], false)).append(" - ");
sb.append(bean.parseDate(st[4], false));
auditInfo[2] = new LabelUser(sb.toString(), font, Color.BRIGHT, Color.BLACK);

String tmp = new String(audit.substring(audit.indexOf("#TX#") + 5, audit.indexOf("|#CU#")));
cbLocals = new ComboBox();
String locals = new String(tmp.substring(0, tmp.indexOf("|#TX#")));

st = Convert.tokenizeString(locals, '|');
cbLocals.add(st);

int size = cbLocals.size();
int pos = 0;
int size1 = 0;
taxs = new String[size][10];
tmp = tmp.substring(tmp.indexOf("#TX#") + 5);
for (int i = 0; i < size; i++) {
pos = 0;
if (i == size - 1) {
locals = new String(tmp.substring(0));
st = Convert.tokenizeString(locals, '|');
size1 = st.length;
for (int a = 0; a < size1; a++) {
taxs[i][pos++] = st[a];
}
} else {
locals = new String(tmp.substring(0, tmp.indexOf("|#TX#")));
st = Convert.tokenizeString(locals, '|');
size1 = st.length;
for (int a = 0; a < size1; a++) {
taxs[i][pos++] = st[a];
}
tmp = tmp.substring(tmp.indexOf("#TX#") + 5);
}
}

cbLocalTax = new ComboBox();
if (size > 0) {
changeLocalTax(0);
}
// //
tmp = audit.substring(audit.indexOf("#CU#") + 5, audit.length() - 1);
st = Convert.tokenizeString(tmp, '|');

cbLocalCurr = new ComboBox();
cbLocalCurr.add(st);
cbLocalCurr.setSelectedIndex(cbLocalCurr.size() - 1);

st = null;
locals = null;
tmp = null;
}

public void onEvent(Event event) {
switch (event.type) {
case ControlEvent.PRESSED :
if (event.target == button[1]) {
unpop();
} else if (event.target == button[0]) {
if (createAuditory()) {
new MessageBox(bean.getString("BOX_TITLE_2"), bean.getString("MESSAGE_23")).popup();
refresh = true;
unpop();
} else {
new MessageBox(bean.getString("BOX_TITLE_1"), bean.getString("MESSAGE_52")).popupNonBlocking();
}
} else if (event.target == cbLocals) {
changeLocalTax(cbLocals.getSelectedIndex());
}
break;
}
}

public boolean isRefresh() {
return refresh;
}

public void initUI() {
initAuditInfoLabels();

add(new LabelUser(bean.getString("FIELD_43"), font.asBold(), Color.BRIGHT, Color.BLACK), LEFT + 5, AFTER + 12);
add(auditInfo[0], 65, SAME);

add(new LabelUser(bean.getString("FIELD_42"), font.asBold(), Color.BRIGHT, Color.BLACK), LEFT + 5, AFTER + 5);
add(auditInfo[1], 65, SAME);

add(new LabelUser(bean.getString("FIELD_6"), font.asBold(), Color.BRIGHT, Color.BLACK), LEFT + 5, AFTER + 5);
add(shopEdit);
shopEdit.setRect(65, SAME, 149, PREFERRED);

add(new LabelUser(bean.getString("FIELD_44"), font.asBold(), Color.BRIGHT, Color.BLACK), LEFT + 5, AFTER + 5);
add(auditInfo[2], 65, SAME);

Container taxContainer = new Container();
taxContainer.setBorderStyle(Container.BORDER_SIMPLE);
taxContainer.setBackForeColors(bean.GREY, bean.GREY);
add(taxContainer);
taxContainer.setRect(LEFT + 5, AFTER + 9, 207, 72);

taxContainer.add(new LabelUser(bean.getString("FIELD_40"), font.asBold(), bean.GREY, bean.PINK), LEFT + 7,
AFTER + 4);

taxContainer.add(cbLocals);
cbLocals.setBackForeColors(bean.GREY, Color.BLACK);
cbLocals.setRect(RIGHT - 7, SAME, 101, 19);
cbLocals.setSelectedIndex(0);

taxContainer.add(new LabelUser(bean.getString("FIELD_16"), font.asBold(), bean.GREY, bean.PINK), LEFT + 7,
AFTER + 4);

taxContainer.add(cbLocalTax);
cbLocalTax.setBackForeColors(bean.GREY, Color.BLACK);
cbLocalTax.setRect(RIGHT - 7, SAME, 101, 19);
cbLocalTax.setSelectedIndex(cbLocalTax.size() - 1);

taxContainer.add(new LabelUser(bean.getString("FIELD_56"), font.asBold(), bean.GREY, bean.PINK), LEFT + 7,
AFTER + 4);

taxContainer.add(cbLocalCurr);
cbLocalCurr.setBackForeColors(bean.GREY, Color.BLACK);
cbLocalCurr.setRect(RIGHT - 7, SAME, 101, 19);
cbLocalCurr.setSelectedIndex(cbLocalCurr.size() - 1);

button = new ButtonUser[2];
add(button[0] = new ButtonUser(bean.getString("ACTION_1"), font.asBold(), bean.GREEN, Color.WHITE));
button[0].setRect(LEFT + 21, BOTTOM - 6, 83, 19);

add(button[1] = new ButtonUser(bean.getString("ACTION_2"), font.asBold(), bean.GREEN, Color.WHITE));
button[1].setRect(RIGHT - 21, BOTTOM - 6, 83, 19);
}
}

Juliana, estamos dispostos a enviar todo o codigo do projecto se tal for necessario. Neste caso precisamos do email para enviar.
Muito obrigado
Logged
JulianaImperial
Full Member
***
Posts: 231



View Profile WWW
« Reply #3 on: February 05, 2010, 04:46:03 pm »

Sabe me dizer se no momento em que o onEvent() é chamado o driver já está aberto? Se for o caso, eis aí o problema. O onEvent() roda em uma thread diferente e você não pode compartilhar uma conexão do Litebase com threads diferentes. Você pode pegar uma nova conexão no onEvent(), mas a tabela não pode ter sido aberta pela thread principal.
Logged
twelon
Newbie
*
Posts: 8


View Profile
« Reply #4 on: February 05, 2010, 05:08:17 pm »

No nosso caso em qualquer método chamado que execute operações sobre a base de dados, estamos sempre a chamar o método "getDriver()" para obter a conexão, ou seja, nunca destruimos a ligação.

Code:
public LitebaseConnection driver = null;

public LitebaseConnection getDriver() {
if (driver == null) {
driver = LitebaseConnection.getInstance(appCrid, null);
}
return driver;
}

Podias-nos indicar então o melhor procedimento a seguir? Destruímos sempre a ligação no fim de a usarmos? Podes indicar-nos um exemplo?

Obrigado pela atenção
Logged
luceliopv
Full Member
***
Posts: 235


luceliopv@hotmail.com
View Profile Email
« Reply #5 on: February 05, 2010, 05:25:18 pm »

Juliana, isso que vc falou funciona no sistema todo? isto é, se eu inicio o sistema e pego a conexão com o banco (só fecho ela quando fecho o sistema), em seguida vou numa tela que tenha um onEvent() e aí faço um select ou insert, isso está errado então? não entendi :s
Logged
KalilMaciel
Full Member
***
Posts: 198


The evil just wins when good men cross their arms.

kalilmaciel@hotmail.com
View Profile Email
« Reply #6 on: February 08, 2010, 11:29:15 am »

Fala pessoal

O objeto de conexão usa um padrão Singleton, ou seja, só pode existir uma instancia de conexão em todo o sistema. Uma sugestão que coloco aqui e que uso direto em meus sistemas é criar uma classe com uma variável estática no início do programa. Assim toda vez que voce quiser usar um comando de banco de dados, basta chamar o objeto de conexão. Um exemplo de como faço essa classe é assim:

Code:
public class Variaveis {

public static LitebaseConnection con;

public static void carregarVariaveis(){
try{
        LitebaseConnection con = LitebaseConnection.getInstance("RSS1", "sistema_teste");
        LitebaseConnection.language = LitebaseConnection.LANGUAGE_PT;

}catch(Exception e){
e.printStackTrace();
}
}

Para usar a conexão, basta fazer como no exemplo a seguir:

Code:
public void criarTabela(){
String sqlCriarTabela = "CREATE TABLE contato (" +
"id_contato int, " +
"id_cliente int, " +
"tipo int, " +
"contatos varchar(100)," +
"PRIMARY KEY(id_contato))";

try {
Variaveis.con.execute(sqlCriarTabela); //usando variável estática
} catch (Exception e) {
e.printStackTrace();
}
}

Desta maneira voce evita de ficar chamando o getDriver toda hora e mantém a certeza de que sempre usará o objeto de conexão disponível.

Espero ter ajudado.

Até mais Smiley

Até mais
Logged
luceliopv
Full Member
***
Posts: 235


luceliopv@hotmail.com
View Profile Email
« Reply #7 on: February 08, 2010, 11:39:26 am »

tbm faço desse jeito kalil, só não entendi isso que a Juliana falou, acho que ela falou que se você obtém o driver novamente depois de aberto num onEvent() é que surge o erro. Talvez seja isso mesmo que esteja acontecendo com o twelon.

Obrigado
Logged
Pwmw
Newbie
*
Posts: 31



View Profile WWW Email
« Reply #8 on: February 08, 2010, 04:08:32 pm »

Estou com alguns problemas de corrompimento de tabela e, apesar de achar que meu problema está relacionado ao método purge(), pode ter ralação com o problema aqui discutido.

Eu também uso o padrão singleton nas minhas conexões, porém em alguns casos durante o uso do sistema, é necessário dar um closeAll() e obter uma nova instancia da conexão, seja para liberar algum arquivo ou até mesmo gravar os dados em disco imediatamente.
Isto pode estar relacionado com o que a juliana falou, com relação à eu estar recriando o driver durante a execução.
Bom, se for isso mesmo que ela quis dizer, o que fazer quando se faz necessário liberar um arquivo ou gravar os dados no disco fisicamente?

Abraços
Logged
KalilMaciel
Full Member
***
Posts: 198


The evil just wins when good men cross their arms.

kalilmaciel@hotmail.com
View Profile Email
« Reply #9 on: February 09, 2010, 06:55:56 pm »

Olá Pessoal

Uma coisa que eu notei é que mesmo quando nós damos um insert no LB, os dados inseridos não são salvos fisicamente no disco. Um problema grave que tenho em minha aplicação é quando o usuário está com o programa aberto e de repente acaba a bateria do dispositivo. Quando isso acontece, em 90% das situações o banco é corrompido e eu preciso recriar o banco.

Com relação ao método purge que o Pwmw falou, aconselho severamente que a tabela seja recriada. Como assim? O método purge serve para remover os espaços vazios deixados na estrutura do banco por uma grande quantidade de comandos delete. Se a quantidade de registros deletados for maior que 50% da quantidade de registros existentes na tabela, é aconselhável apagar a tabela e reinserir os dados. Desse jeito, os índices serão criados mais rápido e elimina-se a fragmentação interna da tabela.

Até mais Smiley
Logged
JulianaImperial
Full Member
***
Posts: 231



View Profile WWW
« Reply #10 on: February 11, 2010, 01:47:48 pm »

Foi isso mesmo que eu falei, compartilhar uma conexão entre Threads pode dar problema sim. Uma sugestão é na hora do onEvent(), fechar a conexão anterior e abrir uma nova somente para aquela Thread. A thread principal do programa pode estar acessando o Litebase quando o onEvent() for chamado. Se o onEvent() acessar o Litebase também, alguma coisa pode se corromper.

Não dá para garantir que vai dar problemas. Por exemplo, se todas as operações do Litebase forem usadas no onEvent(), não deve dar problemas.

Post Merge: February 11, 2010, 01:52:01 pm
Ah, o que o Lucélio falou também pode dar problema. Se você tiver usando uma instância e der um getInstance() dentro de um onEvent() ou outra thread qualquer, mesmo que os parâmetros da conexão sejam os mesmos, a conexão será diferente. Teve cliente que já teve problema com isso. Ao dar o getInstance() dentro do onEvent(), a tabela não era encontrada (já estava aberta pela conexão da thread principal).
« Last Edit: February 11, 2010, 01:52:01 pm by JulianaImperial » Logged
sladeabdala
Guest
« Reply #11 on: March 10, 2010, 01:49:50 pm »

Qual seria a melhor maneira de chamar a conexão no OnEvent() usando singleton?? Alguem tem um exemplo??
Logged
JulianaImperial
Full Member
***
Posts: 231



View Profile WWW
« Reply #12 on: March 11, 2010, 02:41:10 pm »

Como assim?
Logged
sladeabdala
Guest
« Reply #13 on: March 12, 2010, 04:09:22 pm »

na aplicação que dou manutenção tem uma classe conexão assim:

Code:
public final class Conexao {

private static Conexao instance = null;
private LitebaseConnection conexao = null;

private Conexao() {

}

public static Conexao getInstance() {
if (instance == null)
instance = new Conexao();
return instance;
}

public LitebaseConnection getConexao() {
if (conexao == null) {
if (Settings.platform.equals("PalmOS")) {
conexao = LitebaseConnection.getInstance(Settings.applicationId, "chars_type = unicode; path = 2:\\tsfA");
LitebaseConnection.language = LitebaseConnection.LANGUAGE_PT;
// To open the logger.
//LitebaseConnection.setLogger(LitebaseConnection.getDefaultLogger());
} else {
conexao = LitebaseConnection.getInstance(Settings.applicationId, "chars_type = unicode; path = " + Settings.appPath);
LitebaseConnection.language = LitebaseConnection.LANGUAGE_PT;
// To open the logger.
//LitebaseConnection.setLogger(LitebaseConnection.getDefaultLogger());
}
}

return conexao;
}

Nos meus DAOs uso
PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
para recuperar a conexao em todos os métodos.

segue classe clienteDAO:

Code:
public class ClienteDAO {

public ClienteDAO() {}

public boolean exist() throws DAOException {
try{
if(!Conexao.getInstance().getConexao().exists("tb_cliente")){
String sql = "create table tb_cliente(pk_cliente varchar(15) primary key, razaosocial varchar(40) not null, " +
"fantasia varchar(30), endereco varchar(40) not null, fk_cidade varchar(4), fk_bairro varchar(4), " +
"fk_regiao varchar(3), cep varchar(8) not null, telefone varchar(12) not null, fax varchar(12), " +
"contato varchar(25), datanasc int, email varchar(35), obs1 varchar(70), obs2 varchar(70), " +
"obs3 varchar(70), obs4 varchar(70), obs5 varchar(70), obs6 varchar(70), obs7 varchar(70), obs8 varchar(70), " +
"obs9 varchar(70), obs10 varchar(70), fk_atividadecenso varchar(3), fk_portador varchar(3), prazo int not null, " +
"fk_statuscliente varchar(2), dataultimacompra int not null, qtdultimacompra int not null, " +
"valorultimacompra double not null, valormaiorcompra double not null, tipopessoa varchar(1) not null, " +
"vendabancocpf varchar(1) not null, criticaportador varchar(1) not null, limitecredito double not null, " +
"perctroca double not null, dataabertura int not null, datareativacao int not null)";

Conexao.getInstance().getConexao().execute(sql);
return (Conexao.getInstance().getConexao().exists("tb_cliente"));
}
}catch(Exception ex){
throw new DAOException("Erro ao criar a tabela tb_cliente.", ex);
}
return true;
}

public boolean exist(Cliente cliente) throws DAOException {
try{
String sql = "select pk_cliente from tb_cliente where pk_cliente=?";

PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
stmt.setString(0, cliente.getCodCliente());

ResultSet rs = stmt.executeQuery();

if( rs.next() ){
rs.close();
return true;
}else
rs.close();
return false;
}
catch(Exception ex){
throw new DAOException("Erro ao recuperar Cliente.", ex);
}
}

public boolean create(Cliente cliente) throws DAOException {
try {
String sql = "insert into tb_cliente(pk_cliente, razaosocial, fantasia, endereco, " +
"fk_cidade, fk_bairro, fk_regiao, cep, telefone, fax, contato, " +
"datanasc, email, obs1, obs2, obs3, obs4, obs5, obs6, obs7, obs8, " +
"obs9, obs10, fk_atividadecenso, fk_portador, prazo, fk_statuscliente, " +
"dataultimacompra, qtdultimacompra, valorultimacompra, valormaiorcompra, " +
"tipopessoa, vendabancocpf, criticaportador, limitecredito, perctroca, dataabertura, datareativacao) " +
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
stmt.setString(0, cliente.getCodCliente());
stmt.setString(1, cliente.getRazaoSocial());
stmt.setString(2, cliente.getFantasia());
stmt.setString(3, cliente.getEndereco());
stmt.setString(4, cliente.getCidade().getCodCidade());
stmt.setString(5, cliente.getBairro().getCodBairro());
stmt.setString(6, cliente.getRegiao().getCodRegiao());
stmt.setString(7, cliente.getCep());
stmt.setString(8, cliente.getTelefone());
stmt.setString(9, cliente.getFax());
stmt.setString(10, cliente.getContato());
stmt.setInt(11, cliente.getDataNasc());
stmt.setString(12, cliente.getEmail());
stmt.setString(13, cliente.getObs1());
stmt.setString(14, cliente.getObs2());
stmt.setString(15, cliente.getObs3());
stmt.setString(16, cliente.getObs4());
stmt.setString(17, cliente.getObs5());
stmt.setString(18, cliente.getObs6());
stmt.setString(19, cliente.getObs7());
stmt.setString(20, cliente.getObs8());
stmt.setString(21, cliente.getObs9());
stmt.setString(22, cliente.getObs10());
stmt.setString(23, cliente.getAtividadeCenso().getCodAtividadeCenso());
stmt.setString(24, cliente.getPortador().getCodPortador());
stmt.setInt(25, cliente.getPrazo());
stmt.setString(26, cliente.getStatusCliente().getCodStatusCliente());
stmt.setInt(27, cliente.getDataUltimaCompra());
stmt.setInt(28, cliente.getQtdUltimaCompra());
stmt.setDouble(29, cliente.getValorUltimaCompra());
stmt.setDouble(30, cliente.getValorMaiorCompra());
stmt.setString(31, cliente.getTipoPessoa());
stmt.setString(32, cliente.getVendaBancoCpf());
stmt.setString(33, cliente.getCriticaPortador());
stmt.setDouble(34, cliente.getLimiteCredito());
stmt.setDouble(35, cliente.getPercTroca());
stmt.setInt(36, cliente.getDataAbertura());
stmt.setInt(37, cliente.getDataReativacao());

int retorno = stmt.executeUpdate();
if(retorno > 0)
return true;
return false;
} catch (Exception e) {
throw new DAOException("Erro ao inserir Cliente.", e);
}
}

public Cliente restore(Cliente cliente) throws DAOException {
try{
String sql = "select pk_cliente, razaosocial, fantasia, endereco, " +
"fk_cidade, fk_bairro, fk_regiao, cep, telefone, fax, contato, " +
"datanasc, email, obs1, obs2, obs3, obs4, obs5, obs6, obs7, obs8, " +
"obs9, obs10, fk_atividadecenso, fk_portador, prazo, fk_statuscliente, " +
"dataultimacompra, qtdultimacompra, valorultimacompra, valormaiorcompra, " +
"tipopessoa, vendabancocpf, criticaportador, limitecredito, perctroca, " +
"dataabertura, datareativacao " +
"from tb_cliente where pk_cliente=?";

PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
stmt.setString(0, cliente.getCodCliente());

ResultSet rs = stmt.executeQuery();

if( rs.next() ){
cliente.setCodCliente(rs.getString(1));
cliente.setRazaoSocial(rs.getString(2));
cliente.setFantasia(rs.getString(3));
cliente.setEndereco(rs.getString(4));

Cidade cidade = new Cidade();
cidade.setCodCidade(rs.getString(5));
cliente.setCidade(cidade);

Bairro bairro = new Bairro();
bairro.setCodBairro(rs.getString(6));
bairro.setCidade(cidade);
cliente.setBairro(bairro);

Regiao regiao = new Regiao();
regiao.setCodRegiao(rs.getString(7));
cliente.setRegiao(regiao);

cliente.setCep(rs.getString(8));
cliente.setTelefone(rs.getString(9));
cliente.setFax(rs.getString(10));
cliente.setContato(rs.getString(11));
cliente.setDataNasc(rs.getInt(12));
cliente.setEmail(rs.getString(13));
cliente.setObs1(rs.getString(14));
cliente.setObs2(rs.getString(15));
cliente.setObs3(rs.getString(16));
cliente.setObs4(rs.getString(17));
cliente.setObs5(rs.getString(18));
cliente.setObs6(rs.getString(19));
cliente.setObs7(rs.getString(20));
cliente.setObs8(rs.getString(21));
cliente.setObs9(rs.getString(22));
cliente.setObs10(rs.getString(23));

AtividadeCenso atividadeCenso = new AtividadeCenso();
atividadeCenso.setCodAtividadeCenso(rs.getString(24));
cliente.setAtividadeCenso(atividadeCenso);

Portador portador = new Portador();
portador.setCodPortador(rs.getString(25));
cliente.setPortador(portador);

cliente.setPrazo(rs.getInt(26));

StatusCliente statusCliente = new StatusCliente();
statusCliente.setCodStatusCliente(rs.getString(27));
cliente.setStatusCliente(statusCliente);

cliente.setDataUltimaCompra(rs.getInt(28));
cliente.setQtdUltimaCompra(rs.getInt(29));
cliente.setValorUltimaCompra(rs.getDouble(30));
cliente.setValorMaiorCompra(rs.getDouble(31));
cliente.setTipoPessoa(rs.getString(32));
cliente.setVendaBancoCpf(rs.getString(33));
cliente.setCriticaPortador(rs.getString(34));
cliente.setLimiteCredito(rs.getDouble(35));
cliente.setPercTroca(rs.getDouble(36));
cliente.setDataAbertura(rs.getInt(37));
cliente.setDataReativacao(rs.getInt(38));

rs.close();
}else
rs.close();
return cliente;
}
catch(Exception ex){
throw new DAOException("Erro ao recuperar Cliente.", ex);
}
}

public boolean update(Cliente cliente) throws DAOException {
try {
String sql = "update tb_cliente set pk_cliente=?, razaosocial=?, fantasia=?, " +
"endereco=?, fk_cidade=?, fk_bairro=?, fk_regiao=?, cep=?, telefone=?, " +
"fax=?, contato=?, datanasc=?, email=?, obs1=?, obs2=?, obs3=?, " +
"obs4=?, obs5=?, obs6=?, obs7=?, obs8=?, obs9=?, obs10=?, fk_atividadecenso=?, " +
"fk_portador=?, prazo=?, fk_statuscliente=?, dataultimacompra=?, " +
"qtdultimacompra=?, valorultimacompra=?, valormaiorcompra=?, tipopessoa=?, " +
"vendabancocpf=?, criticaportador=?, limitecredito=?, " +
"perctroca=?, dataabertura=?, datareativacao=? " +
"where pk_cliente=?";

PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
stmt.setString(0, cliente.getCodCliente());
stmt.setString(1, cliente.getRazaoSocial());
stmt.setString(2, cliente.getFantasia());
stmt.setString(3, cliente.getEndereco());
stmt.setString(4, cliente.getCidade().getCodCidade());
stmt.setString(5, cliente.getBairro().getCodBairro());
stmt.setString(6, cliente.getRegiao().getCodRegiao());
stmt.setString(7, cliente.getCep());
stmt.setString(8, cliente.getTelefone());
stmt.setString(9, cliente.getFax());
stmt.setString(10, cliente.getContato());
stmt.setInt(11, cliente.getDataNasc());
stmt.setString(12, cliente.getEmail());
stmt.setString(13, cliente.getObs1());
stmt.setString(14, cliente.getObs2());
stmt.setString(15, cliente.getObs3());
stmt.setString(16, cliente.getObs4());
stmt.setString(17, cliente.getObs5());
stmt.setString(18, cliente.getObs6());
stmt.setString(19, cliente.getObs7());
stmt.setString(20, cliente.getObs8());
stmt.setString(21, cliente.getObs9());
stmt.setString(22, cliente.getObs10());
stmt.setString(23, cliente.getAtividadeCenso().getCodAtividadeCenso());
stmt.setString(24, cliente.getPortador().getCodPortador());
stmt.setInt(25, cliente.getPrazo());
stmt.setString(26, cliente.getStatusCliente().getCodStatusCliente());
stmt.setInt(27, cliente.getDataUltimaCompra());
stmt.setInt(28, cliente.getQtdUltimaCompra());
stmt.setDouble(29, cliente.getValorUltimaCompra());
stmt.setDouble(30, cliente.getValorMaiorCompra());
stmt.setString(31, cliente.getTipoPessoa());
stmt.setString(32, cliente.getVendaBancoCpf());
stmt.setString(33, cliente.getCriticaPortador());
stmt.setDouble(34, cliente.getLimiteCredito());
stmt.setDouble(35, cliente.getPercTroca());
stmt.setInt(36, cliente.getDataAbertura());
stmt.setInt(37, cliente.getDataReativacao());
stmt.setString(38, cliente.getCodCliente());

int retorno = stmt.executeUpdate();
if(retorno > 0)
return true;  
return false;
} catch (Exception e) {
throw new DAOException("Erro ao atualizar Cliente.", e);
}
}

public boolean update(ClienteAlterado cliente) throws DAOException {
try {
String sql = "update tb_cliente set telefone=?, fax=?, contato=?, email=? " +
"where pk_cliente=?";

PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);

stmt.setString(0, cliente.getTelefone());
stmt.setString(1, cliente.getFax());
stmt.setString(2, cliente.getContato());
stmt.setString(3, cliente.getEmail());
stmt.setString(4, cliente.getCodCliente());

int retorno = stmt.executeUpdate();
if(retorno > 0)
return true;
return false;
} catch (Exception e) {
throw new DAOException("Erro ao atualizar Cliente.", e);
}
}

public boolean delete(Cliente cliente) throws DAOException {
try {
String sql = "delete from tb_cliente where pk_cliente=?";
PreparedStatement stmt = Conexao.getInstance().getConexao().prepareStatement(sql);
stmt.setString(0, cliente.getCodCliente());

int retorno = stmt.executeUpdate();
if(retorno > 0){
Conexao.getInstance().getConexao().purge("tb_cliente");
return true;
}        
return false;
} catch (Exception e) {
throw new DAOException("Erro ao Excluir a tabela " + this.getClass().getName(), e);
}
}

/**
* Lista o CNPJ e Razão Social de todos os cliente ordenado pela Razão social.
* @param q - O Argumento dever ser o valor 1.
* @return - Um String[][] contendo o CNPJ e Razão Social dos clientes.
*/
public String[][] listAll() throws DAOException {
try{
String[][] retorno = null;
String sql = "select pk_cliente, razaosocial from tb_cliente order by razaosocial";

ResultSet rs = Conexao.getInstance().getConexao().executeQuery(sql);

if(rs.first()){
retorno = rs.getStrings();
rs.close();
}
else
rs.close();
return retorno;
}catch(Exception ex){
throw new DAOException("Erro ao listar Cliente.", ex);
}
}

/**
* Retorna um String[][] com o Nome, Data da Última Compra e CNPJ de todos os clientes
* que realizaram compras no periodo entre inicio e fim, de acordo com o roteiro de visita.
* @param inicio Data inicial.
* @param data Data final.
* @param dayOfWeek Identifica o roteiro de visita.
* @return Um String[][] contendo o Razão Social, Data da última compra, Valor da última compra e CNPJ dos clientes.
*/
public String[][] listAllClientesCompras(Date inicio, Date fim, int dayOfWeek) throws DAOException {
try {
String retorno[][] = null;
String sql = null;
PreparedStatement st = null;
Date date = new Date();
int d;
String diaVisita = null;

if(dayOfWeek == 7)
d = 0;
else
d = dayOfWeek;

if(d == (date.getDayOfWeek()+1))
date.advance(-6);
else if(d == (date.getDayOfWeek()+2))
date.advance(-5);
else if(d == (date.getDayOfWeek()+3))
date.advance(-4);
else if(d == (date.getDayOfWeek()+4))
date.advance(-3);
else if(d == (date.getDayOfWeek()+5))
date.advance(-2);
else if(d == (date.getDayOfWeek()+6))
date.advance(-1);
else
date.advance(d - date.getDayOfWeek());

if(dayOfWeek == 1)
diaVisita = dayOfWeek + "000000";
else if(dayOfWeek == 2)
diaVisita = "0" + dayOfWeek + "00000";
else if(dayOfWeek == 3)
diaVisita = "00" + dayOfWeek + "0000";
else if(dayOfWeek == 4)
diaVisita = "000" + dayOfWeek + "000";
else if(dayOfWeek == 5)
diaVisita = "0000" + dayOfWeek + "00";
else if(dayOfWeek == 6)
diaVisita = "00000" + dayOfWeek + "0";
else if(dayOfWeek == 7)
diaVisita = "000000" + dayOfWeek;

if (fim != null) {
sql = "select razaosocial, valorultimacompra, dataultimacompra, pk_cliente " +
"from tb_cliente c, tb_roteirovisita r " +
"where r.fk_cliente = c.pk_cliente " +
"and c.dataultimacompra > ? " +
"and c.dataultimacompra < ? " +
"and r.diavisita = ? " +
"order by c.dataultimacompra";
st = Conexao.getInstance().getConexao().prepareStatement(sql);
st.setInt(0, inicio.getDateInt());
st.setInt(1, fim.getDateInt());
st.setString(2, diaVisita);
} else {
sql = "select razaosocial, valorultimacompra, dataultimacompra, pk_cliente " +
"from tb_cliente c, tb_roteirovisita r " +
"where r.fk_cliente = c.pk_cliente " +
"and c.dataultimacompra < ? " +
"and r.diavisita = ? " +
"order by c.dataultimacompra";
st = Conexao.getInstance().getConexao().prepareStatement(sql);
st.setInt(0, inicio.getDateInt());
st.setString(1, diaVisita);
}
ResultSet rs = st.executeQuery();

if (rs.first()) {
retorno = rs.getStrings();
rs.close();
} else
rs.close();
return retorno;

} catch (Exception ex) {
throw new DAOException("Erro ao listar Clientes Compras.", ex);
}
}

a maioria dos DAOs são chamados em métodos onEvent(). Assim:

<code>
if (event.target == gridClientes) {
try {
GridEvent ge = (GridEvent)event;
if (gridClientes.getCellText(ge.row, ge.col) != null) {
Cliente cliente = new Cliente();
cliente.setCodCliente(gridClientes.getSelectedItem()[1]);
ClienteDAO clienteDAO = new ClienteDAO();
clienteDAO.restore(cliente);
FrmDetalheCliente frmPedidos = new FrmDetalheCliente(this, cliente);
this.getParentWindow().swap(frmPedidos);
}
} catch (DAOException e) {
MessageBox.showException(e, false);
}
}




Só que isso vive corrompendo tabelas. Alguem tem um exemplo de como fazer isso de uma maneira mais eficaz?
Me sugeriram instanciar o driver dentro do DAO com:
Code:
conexao = LitebaseConnection.getInstance(Settings.applicationId, "chars_type = unicode; path = 2:\\tsfA");

será que isso resolveria o problema??






« Last Edit: March 12, 2010, 04:12:00 pm by sladeabdala » Logged
JulianaImperial
Full Member
***
Posts: 231



View Profile WWW
« Reply #14 on: March 25, 2010, 01:53:06 pm »

Cometi um sério engano. O onEvent() é executado na Thread principal. Então, não há perigo de uma conexão criada na thread principal ser compartilhada com uma thread diferente por causa do onEvent().
Logged
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!