wpjr2’s Weblog

Artigos e tutoriais úteis

JDBC: Conexão e consulta SQL

Escrito por wpjr2 em Maio 9, 2008

Segue abaixo um exemplo de trecho de código para conectar com uma base de dados MySQL e executar uma query de consulta SQL. Estaremos implementando este código na aula de amanhã.


// definir os parametros
String driver = “com.mysql.jdbc.Driver”;
String url =
“jdbc:mysql://localhost:3306/contas” +
“?user=root&password=”;

try {
// verificar o driver do SGBD
Class.forName(driver);
Connection c = DriverManager.getConnection(url);
// testar se a conexao está ativa
System.out.println(”Conexao ativa:” + !c.isClosed()) ;

// criar o sql
String sql = “select * from conta”;

// criar o statement
Statement st = c.createStatement();

// receber o resultado
ResultSet rs = st.executeQuery(sql);

// obter as colunas da tabela
int numColunas = rs.getMetaData().getColumnCount();

String [] colunas = new String[numColunas];

for (int i = 0; i < numColunas; i++)
{
colunas[i] = rs.getMetaData().getColumnName(i+ 1);
System.out.print(colunas[i] + ” | “);
}
System.out.println();

// ler os dados
while (rs.next())
{
int id = rs.getInt(1);
String ag = rs.getString(2);
String cb = rs.getString(3);
String cCorr = rs.getString(4);
double saldo = rs.getDouble(5);
String tipo = rs.getString(6);
String senha = rs.getString(7);
String classif = rs.getString(8);
System.out.println(id + ” - ” + ag + ” - ” + cb + ” - ” + cCorr + ” - ” + saldo + ” - ” + tipo + ” - ” + senha + ” - ” + classif);
}

// fechar a conexao
c.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Deixe um comentário

XHTML: Você pode usar estas tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>