Подтвердить что ты не робот

Запросить MySQL db с помощью java

Ребята, просто положим, у меня есть приложение java с текстовым полем вывода. Я хотел бы запросить Db и отобразить вывод в текстовое поле.

Пример: у меня есть Db с двумя столбцами food и color

Я бы хотел:

SELECT * in Table WHERE color = 'blue'

Любые предложения?

4b9b3361

Ответ 1

Начинающие обычно сталкиваются с проблемами, понимающими, как подключиться к MySQL с Java. Это фрагмент кода, который может быстро запускать вас и запускать. Вы должны получить jar файл mysql jdbc от где-нибудь (google it) и добавить его в путь к классам.

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

Вы должны использовать JDBC. См. http://en.wikipedia.org/wiki/Java_Database_Connectivity

Вам нужен Java-коннектор Java из http://dev.mysql.com/downloads/connector/j/

Затем используйте что-то вроде (скопированное из статьи в Википедии):

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