Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Ederson Sergio Coelho

[Resolvido] Trocando de Banco de Dados com o Java

Recommended Posts

Ola, pessoal é o seguinte eu fiz um chat em java só que ele estava com Banco de Dados Access dai to querendo mudar o Banco de Dados para O MySQL criei o banco tudo só que não estou conseguindo fazer com que ele se conecte ao Banco de Dados alguém poderia me dar uma ajuda no que fazer ?

 

Abaixo estão as classes:

 

package Class;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* @Ederson Sergio Coelho
* @version 1.0
*/
public class ConexaoBD {
       //final String arquivo = "C:\\Users\\Ederson\\Desktop\\Chat\\chat.mdb";
Connection con = null;
ResultSet rs = null;

public ConexaoBD(){
           try {

               Class.forName("com.mysql.jdbc.Driver");  

               //String database = "jdbc:mysql://localhost/chat?user=root&password=m8q9p1e8" + arquivo;

               con = DriverManager.getConnection("jdbc:mysql://localhost/chat?user=root&password=m8q9p1e8");  

           }

           catch (Exception e) {

               System.out.println("Erro: " + e.toString());

           }

       }

public ResultSet consulta(String sql) throws Exception {
           Statement s = con.createStatement();
           rs = s.executeQuery(sql);
           rs.next();
           return rs;}

public int executa(String sql) throws Exception {
           int iLinhasAfetadas = -1;
           Statement s = con.createStatement();
           s.execute(sql);
           iLinhasAfetadas = s.getUpdateCount();
           return iLinhasAfetadas;}

       public int Insert(String sql) throws Exception {
           int iLinhasAfetadas = -1;
           Statement s = con.createStatement();
           s.execute(sql);
           iLinhasAfetadas = s.getUpdateCount();
           return iLinhasAfetadas;}

       public int Delete(String sql) throws Exception {
           int iLinhasAfetadas = -1;
           Statement s = con.createStatement();
           iLinhasAfetadas = s.executeUpdate(sql);
           return iLinhasAfetadas;}

public void fechaConsulta() throws Exception {
           rs.close();}

public void fechaConexao() throws Exception {
           con.close();}
}

 

package Class;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class IniFile {

private List<String> StringList;
private String fileName;

public IniFile(String FileName){
fileName = FileName;
this.ReadStringList(FileName);
}

private void ReadStringList(String FileName){
try {
	fileName = FileName;
	boolean fileexists = (new File(FileName)).exists();
	if (fileexists) {
		InputStream	is = new FileInputStream(FileName);
		Scanner entrada = new Scanner(is);
		StringList = new ArrayList<String>();
		String str;
		while (entrada.hasNextLine()) {
			str = entrada.nextLine().trim();
			if (str.length() > 1){	StringList.add(str); }
		}
	 	is.close();
	}else{
		StringList = new ArrayList<String>();
	}
} catch (IOException e) {JOptionPane.showMessageDialog(null, e.toString());}
}

private void WriteStringList(String FileName){
try {
	OutputStream os = new FileOutputStream(FileName);
	OutputStreamWriter osw = new OutputStreamWriter(os);
	BufferedWriter bw = new BufferedWriter(osw);
	for (String line:StringList){
		bw.write(line);
		if (StringList.indexOf(line)<StringList.size()-1){	bw.newLine(); }
	}
	bw.close();
} catch (IOException e) {JOptionPane.showMessageDialog(null, e.toString());}

}
private void updateLine(int Index,String str){
StringList.set(Index, str);
}
private int indexFromValue(String str){
return StringList.indexOf(str);
}
private String getLine(int Index){
if (StringList.size()> Index){
	return StringList.get(Index);
}else{
	return null;
}
}
private List<String> readIdents(String section){
int i = indexFromValue("[" + section + "]");
if (i >= 0){
	List<String> lista = new ArrayList<String>();
	for (int j=i+1;j<=(StringList.size()-1);j++){
		if (getLine(j).indexOf("[")==0){break;}
		lista.add(getLine(j));
	}
	return lista;
}else{
	return null;
}
}
public String getString(String section,String ident){
List<String> lista = readIdents(section);
String val = null;
if (lista != null){
	for (String line:lista){
		if (line.indexOf(ident+"=") == 0){
			val = line.substring(ident.length() + 1);
			break;
		}
	}
}
return val;
}
public void setString(String section,String ident,String value){
List<String> lista = readIdents(section);
if (lista != null){
	int isct = indexFromValue("[" + section + "]") + 1;
	int lst = lista.size()-1;
	for (String line:lista){
		int idx = lista.indexOf(line);
		if (line.indexOf(ident+"=") == 0){
			updateLine(isct+idx,ident + "=" + value);
			break;
		}
		if (idx == lst){
			StringList.add(isct+lst+1,ident + "=" + value);
		}
	}
}else{
	StringList.add("[" + section + "]");
	StringList.add(ident + "=" + value);
}
WriteStringList(fileName);
}
}

 

package Class;

import Views.Login;

/**
* @author Ederson Sergio Coelho
*/

public class Main {

   public static void main(String[] args) {
       Login log = new Login();
       log.setVisible(true);
   }
}

 

package Class;

import java.util.TimerTask;
import Views.Login;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Timer;
import javax.swing.JOptionPane;

public class Time {

  public static long TEMPO = (1000 * 60);
  private static ResultSet rs;

   public static void main(String[] args) {
       Timer timer = new Timer();
       TimerTask tarefa = new TimerTask() {
           @SuppressWarnings("null")
           public void run() {
                   ConexaoBD BD = new ConexaoBD();
                   try {
                   try {
                       rs = BD.consulta("SELECT COUNT(*) AS CONT FROM TB_MENSAGEM WHERE CD_PARAUSU_MENSAGEM = " + Login.CodUser + " AND LIDO_MENSAGEM = 0");
                       if (rs.getInt("CONT") >= 1) {
                           JOptionPane.showMessageDialog(null,"Você tem novas mensagens!");
                       }
                   } catch (SQLException ex) {
                       JOptionPane.showMessageDialog(null,ex.toString());
                   }
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(null,e.toString());
               }
           }
       };
       timer.scheduleAtFixedRate(tarefa, TEMPO, TEMPO);   
   }
}

 

Está dando o seguinte erro:

 

Ouvindo em javadebug

Executando programa do usuário

Não foi possível enviar o ponto de interrupção FieldBreakpoint Class.ConexaoBD.arquivo, razão: O campo 'arquivo' não existe na classe Class.ConexaoBD.

Programa do usuário finalizado

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.