在Java中从mysql中检索数据

时间:2013-09-18 15:28:31

标签: mysql

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    try
    {
        Class.forName("java.sql.Driver");  
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "parin");
        Statement stmt=con.createStatement();


        String query="Select * from Liblogin;";
        ResultSet rs=stmt.executeQuery(query);
        String username=rs.getString("username");
        String password=rs.getString("password");


        rs.close();
        stmt.close();
        con.close();


        String enteredUsername=t1.getText().toString();
        String enteredPassword = new String(t2.getText());
        if(enteredUsername.contentEquals(username)&&enteredPassword.contentEquals(password))
        {
            Homepage a=new Homepage();
            a.setVisible(true); 
            this.dispose();
        }
        else
        {
            JOptionPane.showMessageDialog(this,"Incorrect name and password.");
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(this, e);
    }
}             

我正在尝试从mysql数据库中检索我的密码和用户名。但由于某些异常而无法执行此操作(Sql异常:在开始结果集之前。)。

1 个答案:

答案 0 :(得分:1)

在尝试从ResultSet行读取值之前,需要调用rs.first();rs.next();

http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#first%28%29

调用rs.next();在while循环中特别方便处理ResultSet中的所有行。

// Get a result set from SQL query
while (rs.next()) {
   // Process this row
}