伙计们,简单地说,我有一个带有文本输出框的java应用程序。我想查询Db并将输出显示到文本框中。
示例我有一个包含两列food
和color
我想:
SELECT * in Table WHERE color = 'blue'
有什么建议吗?
答案 0 :(得分: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) ;
答案 1 :(得分:8)
您应该使用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 */ }
}