【问题标题】:Query a MySQL db using java使用 java 查询 MySQL 数据库
【发布时间】:2011-04-27 19:09:44
【问题描述】:

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

例如,我有一个包含两列 foodcolor 的 Db

我愿意:

SELECT * in Table WHERE color = 'blue'

有什么建议吗?

【问题讨论】:

标签: java mysql database entitymanager


【解决方案1】:

您应该使用 JDBC。见http://en.wikipedia.org/wiki/Java_Database_Connectivity

您需要来自http://dev.mysql.com/downloads/connector/j/ 的 Java MySQL 连接器

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

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

【讨论】:

    【解决方案2】:

    初学者通常在理解如何从 Java 连接到 MySQL 时遇到问题。这是可以让您快速启动并运行的代码 sn-p。您必须从某个地方(谷歌搜索)获取 mysql jdbc 驱动程序 jar 文件并将其添加到类路径中。

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

    【讨论】:

    • 好的,这可能比所有例外都更容易理解,干得好! :)
    • 是的。一个简单的例子。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2012-11-16
    相关资源
    最近更新 更多