-3

我想从他们输入到文本字段中的用户名和密码中检索用户名。我想将这些值作为参数传递给方法,然后该方法将识别用户名以进行打印。请帮忙。像这样的东西......

 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();
4

3 回答 3

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"));
         }
        ...

问候

于 2012-06-15T11:15:52.737 回答
0

假设您想从 db 获取用户的全名,并且您的表结构是这样的:

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
}

注意:这假定传递给方法的密码与存储在 db 中的“形式”相同(即纯文本或散列(+salted))

于 2012-06-15T11:16:02.147 回答
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;
  }       
 }
于 2015-12-02T23:34:31.693 回答