Read results from H2DB

I have a problem with reading the content of the rows in the database. I want to show the information (in the console for the moment) about the employee with given position and name. I have built the path ,started the database in H2 but I am not sure I have used PreparedStatement right .

Table "MyTable" not found

I removed the try/catch to be more readable.

static public void  Search (JButton a , JFormattedTextField name, JComboBox<String> b ) {
    a.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e ) {
            Connection con = null;

            con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");

            Statement stm = null;
            String ime = name.getText();// reads the name 
            String poz = (String) b.getSelectedItem();// reads the position


            String sql1 = String.format("SELECT * FROM  RABOTNICI  WHERE IME = '%s' OR POZICIA = '%s'", ime, poz);
            PreparedStatement prstm = null;

            prstm = con.prepareStatement(sql1);

            ResultSet rs = null;

            rs = prstm.executeQuery(sql1);

2 answers

  • answered 2018-01-14 11:35 haba713


    You are using TCP connection but not starting H2 TCP server like this:

    Normally H2 database is used as embedded without TCP server like this:


  • answered 2018-01-14 11:35 Slava

    I think you had some sources of information and something went wrong down the way.

    • The way you created a preparedStatement, even if it's parsed correctly, is prone to SQL Injections. You should first create the statement and only then inject the values.

      String sql1 = "SELECT * FROM  RABOTNICI  WHERE IME = ? OR POZICIA = ?"
      PreparedStatement prstm = con.prepareStatement(sql1);
      prstm.setString(1, ime);
      prstm.setString(2, poz);

      Please consult this doc page for correct usage of PreparedStatements

    • Also, getConnection's argument looks a bit messed up.

      con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");
    • The following line should appear before the connection creation.


      I suggest using this tutorial for instruction regarding connection to H2 DB

    • And last, I'm not sure how do you get the error about "MyTable" its never mentioned in your code snippet.

    My code quotes were not tested but I believe are clear enough to get the idea.