2011-04-27 11 views
20

Chicos, en pocas palabras, tengo una aplicación java con un cuadro de salida de texto. Me gustaría consultar un Db y mostrar el resultado en un cuadro de texto.Consultar un MySQL db usando java

ejemplo tengo una base de datos con dos columnas y foodcolor

me gustaría:

SELECT * in Table WHERE color = 'blue' 

¿Alguna sugerencia?

+0

En una pregunta similar a otros encontrados [este artículo JDBC-select-fichas] (https://www.tutorialspoint.com/jdbc/jdbc-select-records.htm) muy útil. – surfmuggle

Respuesta

44

principiantes generalmente se enfrentan a problemas de comprensión de cómo conectarse a MySQL desde Java. Este es el fragmento de código que puede ponerlo en funcionamiento rápidamente. Debe obtener el archivo jar del controlador jdbc de mysql desde algún lugar (googlearlo) y agregarlo al classpath.

Class.forName("com.mysql.jdbc.Driver") ; 
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "usrname", "pswd") ; 
Statement stmt = conn.createStatement() ; 
String query = "select columnname from tablename ;" ; 
ResultSet rs = stmt.executeQuery(query) ; 
+2

OK, eso es probablemente un poco más fácil de entender que con todas las excepciones, ¡bien hecho! :) – ert

+2

Sí. Un simple ejemplo por una vez. ¡Gracias! – ThePixelPony

8

Debe usar JDBC. Ve http://en.wikipedia.org/wiki/Java_Database_Connectivity

Es necesario Java MySQL Connector desde http://dev.mysql.com/downloads/connector/j/

A continuación, utilizar algo como (copiado del artículo de Wikipedia):

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

Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/database", 
"myLogin", 
"myPassword"); 
try { 
    Statement stmt = conn.createStatement(); 
try { 
    ResultSet rs = stmt.executeQuery("SELECT * FROM Table WHERE color = 'blue'"); 
    try { 
     while (rs.next()) { 
      int numColumns = rs.getMetaData().getColumnCount(); 
      for (int i = 1 ; i <= numColumns ; i++) { 
       // Column numbers start at 1. 
       // Also there are many methods on the result set to return 
       // the column as a particular type. Refer to the Sun documentation 
       // for the list of valid conversions. 
       System.out.println("COLUMN " + i + " = " + rs.getObject(i)); 
      } 
     } 
    } finally { 
     try { rs.close(); } catch (Throwable ignore) { /* Propagate the original exception 
instead of this one that you may want just logged */ } 
    } 
} finally { 
    try { stmt.close(); } catch (Throwable ignore) { /* Propagate the original exception 
instead of this one that you may want just logged */ } 
} 
} finally { 
    //It's important to close the connection when you are done with it 
    try { conn.close(); } catch (Throwable ignore) { /* Propagate the original exception 
instead of this one that you may want just logged */ } 
} 
+0

Siempre es una buena práctica cerrar los recursos –

Cuestiones relacionadas