根据参数从mysql数据库中检索特定值

时间:2012-06-15 11:06:02

标签: java mysql database

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

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

3 个答案:

答案 0 :(得分: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"));
         }
        ...

此致

答案 1 :(得分: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))

答案 2 :(得分: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;
  }       
 }