2013-07-19 99 views
0

我對Java並不擅長我只學過基礎知識,它仍然有點新鮮。我想知道某人如何從表中打印一行到Java控制檯。如何將數據從數據庫打印到Java控制檯?

try { 
    statement = con.prepareStatement(
       "SELECT * FROM users WHERE Username ='" + 
       LOGIN_UsernameField.getText() + "' AND Password ='" + 
       LOGIN_PasswordField.getPassword() + "'"); 
    System.out.println(); 
} 

system.out.println的事情我知道,沒有當然的工作,我需要的東西來取代它打印出來自正上方的SQL語句行。

+3

如何在你問之前將它炸死? http://www.mkyong.com/tutorials/jdbc-tutorials/ – Reddy

+1

可能是他不知道哪些關鍵字用於搜索(我的意思是「JDBC」) – Karloss

+0

@Karloss,我沒有投反對票,也沒有做出任何侵略評論。這就是爲什麼我給了鏈接。 :) – Reddy

回答

2

從Oracle嘗試this tutorial。這很簡單直接。

這將是這樣的

try{ 
     statement = con.prepareStatement(
       "SELECT * FROM users WHERE Username = ? AND Password =?"); 
     statement.setString(0,LOGIN_UsernameField.getText()); 
     statement.setString(0,LOGIN_PasswordField.getPassword()); 
     ResultSet rs = statement.execute(); 
     while(rs.next()){ 
      System.out.println("UserName:"+rs.getString("Username")+"\nPassword:"+rs.getString("Password")); 
     } 
}catch(){ 
//handle exceptions 
}finally{ 
//close statements, statement and resultset here.. 
} 
+0

謝謝,謝謝,我其實嘗試過bing和谷歌,我只是找不到合適的地方,我使用了錯誤的關鍵字。無論如何,再次感謝你。 –

1

下面是代碼

System.out.println("-------- MySQL JDBC Connection Testing ------------"); 


    Connection connection = null; 

    try { 
     connection = DriverManager 
       .getConnection("jdbc:mysql://localhost:3306/testDb", "userName", "Password"); 
    } catch (SQLException e) { 
     for(Throwable ex : e) { 
      System.err.println("Error occurred " + ex); 
     } 
     e.printStackTrace(); 
    } 

    if (connection != null) { 
     System.out.println("Connected to database!"); 
    } else { 
     System.out.println("Failed to make connection!"); 
    } 

    try { 
     Statement stmt = connection.createStatement(); 
     String query = "select * from person ;"; 
    //person is the table name 
     ResultSet rs = stmt.executeQuery(query); 
     while (rs.next()) { 
      String name = rs.getObject(1).toString(); 
      String gender = rs.getObject(2).toString(); 
      System.out.println("Name of the person is " + name + " and his gender is " + gender); 
    //Person table has name and gender column 

     } 
    } catch (SQLException e) { 
     e.printStackTrace(); 
     for(Throwable ex : e) { 
      System.err.println("Error occurred " + ex); 
     } 
     System.out.println("Error in fetching data"); 
    } 

注:我使用JDBC 4附帶Java 7,因此沒有必要明確地提供驅動程序。編譯器會自動從類路徑中獲取它。您可以下載MySqlConnector.jar並將其放入您的類路徑中。如果您未使用Java 7,則必須使用Class.forName()明確加載驅動程序。當然,我正在使用MySql ...驅動程序將隨着您使用的數據庫而改變。

希望這會有所幫助。