Search code examples
mysqljspjdbcdatabase-connectionsqlexception

jdbc to MYSQL error: "table airportdetails doesn't exist"



I am trying to connect to a MySQL database from a jsp page using jdbc in the backend.
I have the following code:

public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
    Connection con = null;
    if (del.length() == 0) {
        del="no data";  
    }
    name = name.replaceAll("\\(.+?\\)", "");
    name = name.replaceAll(" ", "_");
    del = del.replaceAll(" ", "_");
    System.out.println("del "+del);

    String url = "jdbc:mysql://localhost:3306/test";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url,"root","");
        con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
                "name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
        ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

I am getting the following error at

ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();

error:

Table 'test.airportdetails' doesn't exist

But from my phpmyadmin I can see that the table is created and exists: enter image description here What is the reason I am getting this error?
Thank you.


Solution

  • executeUpdate()

    Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

    Currently you are trying to use this for creating a table. That's the reason why you are getting that error.

    Refer to the documentation Java 6 OR Java 1.4.2 for executeUpdate

    EDIT:

    You should create a table using Statement

    Statement st = con.createStatement();
    String table = "Create table .......";
    st.executeUpdate(table);