2012-06-15 68 views
-3

我想從用戶名和密碼中檢索用戶名,他們已經輸入到文本框中。我想將這些值作爲參數傳遞給方法,然後該方法將識別打印輸出的用戶名稱。請幫忙。這樣的事情...從基於參數的mysql數據庫檢索特定值

public void getUser(String username, String password)throws SQLException{ 
String qry = "SELECT UserName From USER...."; 

    Connection con = null; 
    PreparedStatement stmt = null; 

    try{ 

con = DriverManager.getConnection("URL"); 
stmt = con.prepareStatement(qry); 
stmt.executeUpdate(); 
+0

你的方法簽名和你的意圖是完全互相矛盾。 – adarshr

+0

忽略方法名稱 – user1106130

+0

用戶名已在文本字段中,爲什麼你需要它? – mtariq

回答

0

如果不是是更新或插入,不使用的executeUpdate()

必須使用的executeQuery()。

試試這個:

Connection con = null; 
PreparedStatement stmt = null; 
ResultSet rs = null; 
String qry = "SELECT UserName From USER where username=? and password=?"; 
    try{ 

     con = DriverManager.getConnection("URL"); 
     stmt = con.prepareStatement(qry); 
     stmt.setString(1, username); 
     stmt.setString(2, password); 
     rs = stmt.executeQuery(); 
     while (rs.next()) { 
       System.out.println(rs.getString("UserName")); 
     } 
     ... 

問候

+0

沒有一個while循環? – user1106130

+0

可以跟一個if,但是表可以多一行,依賴值到數據庫中(相同的用戶和密碼,但是不同的角色) – esmoreno

0

假設你想從數據庫獲取用戶的全名和你的表結構是這樣的:

fullname | username | password

你可以做到以下幾點:

Connection c = null; 
PreparedStatement s = null; 
try { 
    c = DriverManager.getConnection("URL"); 
    s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?"); 
    s.setString(1, username); 
    s.setString(2, password); 

    ResultSet rs = s.executeQuery(); 
    if(rs.next()) 
    return rs.getString("fullname"); 

    return null; // no user found! 
} catch(SQLException e) { 
    System.err.println(e.getMessage()); 
} finally { 
    // close s and c 
} 

注意:這假定傳遞給方法的密碼與存儲在數據庫中的密碼相同(即「形式」)。純文本或散列(+鹽醃))

+0

return rs.getString(「fullname」); <<<提供錯誤,即使我將「全名」更改爲我的數據庫反映的數據 – user1106130

+0

這是因爲您的方法具有'void'返回類型。將其更改爲返回字符串或直接在方法中處理名稱! – hage

+0

它仍然需要返回聲明?這是最後阻止後? – user1106130

0

試試這個它非常簡單的例子

private boolean validate_login(String id,String password) { 

try{   
    Class.forName("org.sqlite.JDBC"); // MySQL database connection 
    Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");  
    PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?"); 
    pst.setString(1, id); 
    pst.setString(2, password); 
    ResultSet rs = pst.executeQuery();       
    if(rs.next())    
     return true;  
    else 
     return false; 


try{   
    Class.forName("org.sqlite.JDBC"); // MySQL database connection 
    Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");  
    PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?"); 
    pst.setString(1, id); 
    pst.setString(2, password); 
    ResultSet rs = pst.executeQuery();       
    if(rs.next())    
     return true;  
    else 
     return false; 
    } 
    catch(Exception e){ 
    e.printStackTrace(); 
    return false; 
    }  
}