2016-07-24 75 views
-5

例如specefic行或列的數據如何獲得SQL

id name surname 
0 Alex A 
1 Mark B 
2 Bill C 

讓我們假設我想其中id等於在Java中1名和姓,我怎麼能得到各列的值

+2

您使用JDBC:使用Java™教程 - JDBC(TM)數據庫訪問(HTTPS: //docs.oracle。 COM/JavaSE的/教程/ JDBC /)。 – Andreas

回答

0

使用Statement或PreparedStatement,你可以檢索字段下面提供你應該已經包括JDBC庫項目中的

try{ 
    Class.forName("com.mysql.jdbc.Driver"); // loading driver class 
    Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Database_name", username,password); // getting connection may change depending on database you are using 
    PreparedStatement ps = cn.prepareStatement("select name,sirname from user where id = ?"); 

       ps.setString(1,id); 

      ResultSet rs = ps.executeQuery(); 
       int i=0; 
       while(rs.next()) 
       { 
        String name = rs.getString("name"); 
        // retrieve your fields 
       } 

}catch(Exception e) 
{ 
    e.printStackTrace(); 
} 
+0

如果你想要顯示某人,顯然甚至不知道JDBC是否存在,如何使用JDBC,你應該至少給出一個很好的例子來說明*應該如何被使用。使用試用資源。另外,不懂JDBC的人不會發現它有用,因爲他們不知道「cn」是什麼。但是,由於StackOverflow不是一個教學網站,無論如何這都是無關緊要的。 – Andreas

+0

@Andreas感謝您的建議,我添加了更多的數據。 – Shailesh