-1

我想在将详细信息插入表格之前检查用户名和密码。如果用户名和密码与另一个表中的用户名和密码匹配,则只允许插入详细信息。怎么办?请提供代码。

我正在使用 net beans 7.0.1 和 mysql 数据库。

我的代码是:-

String query1,pass1;

query1 = "select username,password from login";
stmt.executeQuery(query1);


             ResultSet rs = stmt.getResultSet();


             while(rs.next())   
             {
               user1 = rs.getString("username") ;

               pass1 = rs.getString("password");

               if(user1.equals("username") && user1.equals("password"))
               {
                 query = "insert into units (IO_number,Physical_progress,Financial_progress,Final_Completion_Date)values('"+IO_number+"','"+Physical_progress+"','"+Financial_progress+"','"+Final_Completion_Date+"')"; 

                 int i = stmt.executeUpdate(query);

               }
             }
4

1 回答 1

0

您已经掌握了第一个查询的基础知识,但从现在看来,它很危险而且很麻烦,因为它容易受到 SQL 注入的攻击。

在此示例中,我将向您展示如何使用preparedstatements 进行查询(这更安全)以及如何检查是否存在任何用户对于给定的用户名和密码组合)

try {
      //this portion assumes you know how to set up a connection to your database
      //provider
      conn = getConnection();
      String query = "select count(*) from tableName where username = ? and password = ?";
      pstmt = conn.prepareStatement(query);
      pstmt.setString(1, username); //puts the username at the position of the first question mark
      pstmt.setString(2, password); //and the password at the position of the second one.
      rs = pstmt.executeQuery();
      if (rs.next()) {
        int numberOfRows = rs.getInt(1);
        System.out.println("numberOfRows= " + numberOfRows);
        if(numberOfRows == 0)
        {
          System.out.println("No user found for this username and password");
        }
        else
        {
          //you could set a flag here to indicate that you found a username and password
        } 
      } else {
        System.out.println("error: could not get the record counts");
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        rs.close();
        pstmt.close();
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

如需进一步阅读,我建议您查看Oracle 自己的文档

于 2013-06-21T08:18:45.123 回答