web-dev-qa-db-fra.com

Recherchez une base de données MySQL en utilisant java

Les gars, tout simplement, j'ai une application Java avec une zone de sortie de texte. Je voudrais interroger un Db et afficher la sortie dans une zone de texte.

Exemple J'ai un Db avec deux colonnes food et color

J'aimerais :

SELECT * in Table WHERE color = 'blue'

Aucune suggestion?

22
Lexicon

Les débutants rencontrent généralement des problèmes pour comprendre comment se connecter à MySQL à partir de Java. Il s'agit de l'extrait de code qui peut vous permettre de démarrer rapidement. Vous devez récupérer le fichier jar du pilote mysql jdbc quelque part (google it) et l'ajouter au chemin de classe.

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) ;
49
euphoria83

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

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

Ensuite, utilisez quelque chose comme (copié à partir 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
ert