24

Guys, simply put, I have a java application with a text output box. I'd like to query a Db and display the output into a text box.

Example I have a Db with two columns food and color

I'd like to :

SELECT * in Table WHERE color = 'blue'

Any suggestions?

jotapdiez
  • 1,426
  • 12
  • 27
Lexicon
  • 1,924
  • 5
  • 26
  • 36
  • In a similar question others found [this article jdbc-select-records](https://www.tutorialspoint.com/jdbc/jdbc-select-records.htm) usefull. – surfmuggle Nov 06 '16 at 02:04

2 Answers2

54

Beginners generally face problems understanding how to connect to MySQL from Java. This is the code snippet that can get you up and running quickly. You have to get the mysql jdbc driver jar file from somewhere (google it) and add it to the 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) ;
euphoria83
  • 13,314
  • 16
  • 58
  • 70
11

You should use JDBC. See http://en.wikipedia.org/wiki/Java_Database_Connectivity

You need the Java MySQL Connector from http://dev.mysql.com/downloads/connector/j/

Then use something like (copied from the Wikipedia article):

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 */ }
}
ert
  • 496
  • 4
  • 13