夥計們,簡單地說,我有一個帶有文本輸出框的java應用程序。我想查詢一個Db並將輸出顯示到文本框中。使用java查詢MySQL數據庫
比如我有一個兩列food
和color
一個Db的,我想:
SELECT * in Table WHERE color = 'blue'
有什麼建議?
夥計們,簡單地說,我有一個帶有文本輸出框的java應用程序。我想查詢一個Db並將輸出顯示到文本框中。使用java查詢MySQL數據庫
比如我有一個兩列food
和color
一個Db的,我想:
SELECT * in Table WHERE color = 'blue'
有什麼建議?
初學者普遍面臨瞭解如何從Java連接到MySQL的問題。這是可以讓你快速啓動並運行的代碼片段。您必須從某處獲取mysql jdbc驅動程序jar文件(google它)並將其添加到類路徑中。
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) ;
好的,這可能比所有例外更容易理解,做得好! :) – ert 2011-04-27 19:20:57
是的。一個簡單的例子。謝謝! – ThePixelPony 2014-05-24 10:07:36
您應該使用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 */ }
}
關閉資源總是一個很好的做法 – 2016-07-11 07:40:19
在一個類似的問題,其他人發現[本文JDBC的選擇 - 記錄(https://www.tutorialspoint.com/jdbc/jdbc-select-records.htm)有用。 – surfmuggle 2016-11-06 02:04:10