Interroger une base de données MySQL à l'aide de java


Les gars, tout simplement, j'ai une application java avec une boîte de sortie de texte. Je voudrais interroger une base de données et afficher la sortie dans une zone de texte.

Exemple j'ai une base de données avec deux colonnes food et color

J'aimerais :

SELECT * in Table WHERE color = 'blue'

Des suggestions?

Author: jotapdiez, 2011-04-27

2 answers

Les débutants rencontrent généralement des problèmes pour comprendre comment se connecter à MySQL à partir de Java. C'est l'extrait de code qui peut vous aider à démarrer rapidement. Vous devez obtenir le fichier jar du pilote mysql jdbc de quelque part (google it) et l'ajouter au 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) ;
 46
Author: euphoria83, 2011-04-27 19:14:39

Vous devez utiliser JDBC. Voir http://en.wikipedia.org/wiki/Java_Database_Connectivity

Vous avez besoin du connecteur Java MySQL de http://dev.mysql.com/downloads/connector/j/

Ensuite, utilisez quelque chose comme (copié de l'article 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 */ }
}
 8
Author: ert, 2011-04-27 19:19:27