使用 java 查询 MySQL 数据库
2022-09-01 18:09:16
伙计们,简单地说,我有一个带有文本输出框的java应用程序。我想查询数据库并将输出显示在文本框中。
示例 I 有一个包含两列的 Db,并且food
color
我想 :
SELECT * in Table WHERE color = 'blue'
有什么建议吗?
伙计们,简单地说,我有一个带有文本输出框的java应用程序。我想查询数据库并将输出显示在文本框中。
示例 I 有一个包含两列的 Db,并且food
color
我想 :
SELECT * in Table WHERE color = 'blue'
有什么建议吗?
初学者通常会遇到如何从Java连接到MySQL的问题。这是可以让您快速启动和运行的代码片段。你必须从某个地方获取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) ;
您应该使用 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 */ }
}