使用java查询MySQL数据库

Lex*_*con 22 java mysql database entitymanager

伙计们,简单地说,我有一个带有文本输出框的java应用程序.我想查询Db并将输出显示到文本框中.

示例我有一个带有两列food和的Dbcolor

我想 :

SELECT * in Table WHERE color = 'blue'
Run Code Online (Sandbox Code Playgroud)

有什么建议?

eup*_*a83 49

初学者通常会遇到理解如何从Java连接到MySQL的问题.这是可以帮助您快速启动和运行的代码段.你必须从某个地方获取mysql jdbc驱动程序jar文件(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) ;
Run Code Online (Sandbox Code Playgroud)

  • 好吧,这可能比所有例外更容易理解,做得好!:) (2认同)
  • 是啊.一次简单的例子.谢谢! (2认同)

ert*_*ert 9

你应该使用JDBC.请参见http://en.wikipedia.org/wiki/Java_Database_Connectivity

您需要http://dev.mysql.com/downloads/connector/j/上的Java MySQL Connector

然后使用类似的东西(从维基百科文章中复制):

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 */ }
}
Run Code Online (Sandbox Code Playgroud)