How to perform a search in an SQL database with a java application?

39,191

Solution 1

Have a look at this link

It is using classes such as Connection and PreparedStatement

Pseudo-code being

String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";

dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);

// execute select SQL stetement
ResultSet rs = preparedStatement.executeQuery();

try {
  while (rs.next()) {
    String userid = rs.getString("USER_ID");
    String username = rs.getString("USERNAME");
    System.out.println("userid : " + userid);
  }

  } catch (SQLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
  } finally {
    preparedStatement.close();
    dbConnection.close();
  }

Solution 2

http://docs.oracle.com/javase/tutorial/jdbc/basics/

Look into how to use JDBC.

A very basic example:

    Connection c = null; //need to initialize a java.sql.Connection from JDBC.


    String sql = "SELECT * FROM Users WHERE name = ?";        
    PreparedStatement ps = c.prepareStatement(sql);
    ps.setString(1, "John Smith");

    ResultSet rs = ps.executeQuery();

    List<String> matchingNames = new ArrayList<>();
    while (rs.next())
    {
        String name = rs.getString("name");
        matchingNames.add(name);
    }       

    for (String name: matchingNames)
    {
        //Display dialog.
    }
Share:
39,191
Storio
Author by

Storio

Updated on July 07, 2022

Comments

  • Storio
    Storio almost 2 years

    I'm planning to build a very very simple java application done on Netbeans that accepts basic individual information like ID number, name, and address and stores it on an sql database.

    I want to put a search function on my program that accepts ID numbers. When the user inputs the ID number that is stored in the database, it will show the Name and address on a pop up message dialog.

    I know this is possible but can you link me to some guides or documentations about the search function? or maybe you could give me a very short example of a sample code done in the search button?

    • Scary Wombat
      Scary Wombat over 10 years
      Is this going to be for simple queries like ID = ? or more dynamic and complex queries based upon whatever fields are filled in?
    • Storio
      Storio over 10 years
      Yeah just a very simple query like that. No need for dynamic search. The program just accepts the exact ID number.