开发者

Query a MySQL db using java

开发者 https://www.devze.com 2023-03-01 16:07 出处:网络
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.

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?


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


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 */ }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消